![](/img/trans.png)
[英]How to copy and write file in the same directory using fs module in nodejs?
[英]Uploading document in NodeJs using Fs module : Error: write after end
我一直在嘗試使用以下代碼上傳文檔。
我做了谷歌搜索,還沒有找到任何解決方案。
app.post('/documents', function (req, res) {
var document = {};
var fstream = null;
// populate fields
form.on("field", function (name, value) {
document[name] = value ;
});
form.on("part", function (part) {
if (!part.filename) {
return;
}
var path = __dirname + '/files/' + part.filename;
fstream = app.npm.fs.createWriteStream(path);
document.type = part.headers["content-type"]
document.name = part.filename;
document.size = part.byteCount;
document.path = path;
fstream.on("close", function () {
db.sequelize.models.Document.create(document).then(function (newDocument) {
res.send(newDocument)
res.end();
},
function (error) {
res.send(error);
});
});
part.pipe(fstream);
});
form.on("close", function (data) {
fstream.end();
fstream = null;
});
form.parse(req);
});
注意:我正在使用fs模塊。 https://nodejs.org/api/fs.html
第一張圖片正常。 但是當我嘗試上傳另一個圖像時,它會引發異常:
events.js:72 throw er; //未處理的“錯誤”事件^
錯誤:在Form.Writable.write(_stream_writable.js:180:5)的writeAfterEnd(_stream_writable.js:180:5)在寫入(_stream_read.js:601:24)在流(_stream_read.js:610)處結束寫入:7)在IncomingMessage.pipeOnReadable(_stream_read.js:642:5)在IncomingMessage.emit(events.js:92:17)在emitReadRead_(_stream_visible.js:426:10)在emitReadRead(_stream_read.js:422:5) )在IncomingMessage.Readable.push(_stream_visible.js:127:10)上的可讀AddChunk(_stream_visible.js:165:9)上
找到了解決方案。
var form = new app.npm.multiparty.Form();
這是在全球范圍內定義的。 至於每個新請求,我應該創建表單的新實例,因為在上一次調用中流已關閉,所以我應該通過獲取最新內容來創建新實例。
解決方案如下所示:
app.post('/ documents',function(req,res){
var document = {};
var form = new app.npm.multiparty.Form();
var fstream = null;
...
其余的都一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.