使用下面的代码,我可以将图像上传到mogodb一次,如果我第二次尝试收到错误。
我做了一些研究,因为写入流正在关闭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方法以在id上运行代码,我该如何解决这个问题?
答案 0 :(得分:0)
替换
var form = new multiparty.Form();
内
app.post('/upload', function(req,res){...});
不要在全球范围内声明var form
。它应该初始化每个帖子请求