画像をディスクにアップロードし、その URL を MongoDB に保存するのが最善の方法です。画像を再度取得するときに休憩します。URLを指定するだけで画像が取得できます。アップロード用のコードは次のとおりです。
app.post('/upload', function(req, res) {
// Get the temporary location of the file
var tmp_path = req.files.thumbnail.path;
// Set where the file should actually exists - in this case it is in the "images" directory.
target_path = '/tmp/' + req.files.thumbnail.name;
// Move the file from the temporary location to the intended location
fs.rename(tmp_path, target_path, function(err) {
if (err)
throw err;
// Delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files.
fs.unlink(tmp_path, function() {
if (err)
throw err;
//
});
});
});
ターゲット パスを MongoDB データベースに保存します。
ここでも、画像を取得する際に、MongoDB データベースから URL を抽出し、このメソッドで使用します。
fs.readFile(target_path, "binary", function(error, file) {
if(error) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.write(error + "\n");
res.end();
}
else {
res.writeHead(200, {"Content-Type": "image/png"});
res.write(file, "binary");
}
});