2016-08-05 85 views
2

試圖圍繞我得到的這個錯誤,我不明白爲什麼。我看到了幾個帖子,但他們都是不同的情況,沒有一個與我的相匹配。所以感謝幫助。 我想上傳多個文件上傳。 但我做文件上傳它只是一個工作。 但是當我嘗試上傳多個文件時,它不起作用 你能給我一個答案嗎?Node.js 344錯誤發送後無法設置標題

router.post('/contents/insert/upload', ensureAuthenticated, function(req, res, next) { 
 
\t 
 
\t var form = new formidable.IncomingForm(); 
 
\t 
 
\t form.parse(req); 
 
// \t form.on("fileBegin", function (name, file){ 
 
// \t \t console.log('upload come on3'); 
 
// \t \t 
 
// }); 
 
    form.on("file", function (name, file){ 
 
     fs.readFile(file.path, function(error, data){ 
 
     \t var filePath = __dirname + '/../public/uploads/' + file.name; 
 
     \t 
 
     \t fs.writeFile(filePath, data, function(error){ 
 
     \t \t if(error){ 
 
     \t \t \t throw err; 
 
     \t \t \t //res.redirect('back'); 
 
     \t \t }else { 
 
     \t \t \t res.redirect('back'); 
 
     \t \t } 
 
     \t }); 
 
     }); 
 
    }); 
 

 
});
<form action="/adm/contents/insert/upload" method="post" enctype="multipart/form-data" > 
 
\t \t \t  <!-- <input type="file" name="file" /> 
 
\t \t \t  <input type="submit" /> --> 
 
\t \t \t \t <div class="file-field input-field"> 
 
\t \t \t  \t <div class="btn"> 
 
\t \t \t \t \t \t <span>input images</span> 
 
\t \t \t \t  \t <input type="file" name="file" multiple> 
 
\t \t \t  \t </div> 
 
\t \t \t  \t <div class="file-path-wrapper"> 
 
\t \t \t   \t <input class="file-path validate" type="text"> 
 
\t \t \t  \t </div> 
 
\t \t \t  </div> 
 
\t \t \t  <input type="submit" class="btn waves-effect waves-light" value="upload" /> 
 
\t \t \t </form>

回答

2

file將觸發事件在上傳的每個文件,所以最終代碼會發出res.redirect()每個上傳的文件。這將導致錯誤(您只能發出重定向,或發送迴應,在請求的生命週期中只發送一次)。

相反,你要聽的end事件,並出具有重定向:

form.on("file", function (name, file) { 
    ...handle the file copy here, but don't call `res.redirect()` anywhere... 
}); 

form.on("end", function() { 
    res.redirect('back'); 
}); 

FWIW,在我看來,你要設置的厲害的uploadDir選項,或使用fs.rename(),而不是在上傳後讀取文件並將其寫入新的位置(這不是非常有效)。

+0

我添加代碼}否則{ \t \t \t form.on( 「結束」,函數(){ \t \t \t \t res.redirect( '返回'); \t \t \t \t}); \t \t}你寫的是什麼。非常感謝。但我不知道爲什麼瀏覽器正在繼續加載......即使插入了 –

+0

您不應該在同一級別添加'end'處理程序_inside_''''處理程序。我會編輯我的答案來澄清。 – robertklep

+0

非常感謝!它的工作澄清!選擇了你的答案 –

相關問題