1
使用下面的代碼,我可以上傳一個圖像到mogodb一次,如果我再試一次,我得到一個錯誤。寫完後,nodejs gridFS寫入流錯誤
我做了一些研究,其因爲writestream正在關閉NODEJS writeStream error
conn.once('open', function() {
var gfs = Grid(conn.db, mongoose.mongo);
app.post('/upload', function(req,res){
form.on('part', function(part){
if(!part.filename) return;
size = part.byteCount;
fileName = part.filename;
});
form.on('file', function(name,file){
var tempfile = file.path;
var origname = fileName;
var writestream = gfs.createWriteStream({ filename: origname });
fs.createReadStream(tempfile).on('end', function() {
res.send('<p><h1>Upload Complete!</h1><p>');
}).on('error', function() {
res.send('Error, upload failed!');
}).pipe(writestream);
});
form.parse(req);
});
app.get('/image/:id', function(req,res){
console.log(req.params.id)
gfs.createReadStream({_id:req.params.id}).pipe(res);
});
});
錯誤消息看起來像這樣
events.js:72
throw er; // Unhandled 'error' event
^
Error: write after end
at writeAfterEnd (C:\Users\Michael\Desktop\Chat-App\node_modules\multiparty\node_modules\readable-stream\lib\_stream_writable.js:161:12)
at Form.Writable.write (C:\Users\Michael\Desktop\Chat-App\node_modules\multiparty\node_modules\readable-stream\lib\_stream_writable.js:208:5)
at write (_stream_readable.js:582:24)
at flow (_stream_readable.js:591:7)
at _stream_readable.js:559:7
at process._tickCallback (node.js:419:13)
所以看起來多方是我的代碼有問題。我的問題是我應該如何解決這個問題,我應該改變我的post方法來運行代碼上的代碼?