2015-10-15 84 views
0

刮圖像後,我可以使用請求下載到文件夾。我想將此圖片的位置傳遞給我的Mongoose收藏。將刮圖像的位置保存到數據庫節點/ MEAN

在回調中,我認爲應該有一種方法來保存位置,以便在保存模型對象時可以傳遞此信息。

exports.createLook = function(req, res) { 
    var url = req.body.image; 
    var randomizer = '123456'; 

    var download = function(url, filename, callback) { 

    request(url) 
     .pipe(fs.createWriteStream(filename)) 
     .on('close', callback); 
    }; 

    download(url, '../client/assets/images/' + randomizer + '.jpg', function() { 
    console.log('done'); 
    // do something? 
    }); 

    // now get model details to save 
    var newLook = new Look(); 
    newLook.title = req.body.title; 
    newLook.image =  // image location 

    newLook.save(function(err, look) { 
    if(err) return res.send(500); 
    } else { 
    res.send(item); 
    } 
} 
+0

不知道如果我理解你。看看你的代碼,你可以設置'newLook.image =「../client/assets/images/'+ randomizer +'.jpg」' –

+0

我將改變randomizer到創建一個隨機字符串的東西。因此,首先我下載並保存圖像到我的文件夾,然後將其保存到我的模型,所以randomizer會改變。 – venturz909

回答

1

假設「隨機」,會產生,我會做:

exports.createLook = function(req, res) { 
    var url = req.body.image; 
    var randomizer = getSomthingRandom(); 

    var download = function(url, filename, callback) { 

    request(url) 
     .pipe(fs.createWriteStream(filename)) 
     .on('close', callback(filename); 
    }; 

    download(url, '../client/assets/images/' + randomizer + '.jpg', function(filename) { 
    console.log('done'); 
    // now get model details to save 
    var newLook = new Look(); 
    newLook.title = req.body.title; 
    newLook.image = filename; 
    .... 
    }); 
+0

謝謝,這是很好的解決方案。我確實遇到了一個令人討厭的問題:「發送後無法設置標題」消息,該消息將嘗試修復。 – venturz909

+0

很高興我能幫到你。如果這回答你的問題,那麼請接受它作爲正確的答案。 –