2014-09-23 129 views
3

我在Express.js 4中使用connect-busboy來上傳文件。我在app.js中添加了app.use(busboy({ immediate: true });。我的路由處理程序是這樣的:爲什麼req.busboy未定義?

router.post('/upload', function (req, res) { 
    var fstream; 

    req.pipe(req.busboy); 
    console.log(req.busboy); 
    req.busboy.on('file', function (fieldName, file, fileName) { 
     console.log('Uploading ' + fileName + '...'); 
     fstream = fs.createWriteStream(__dirname + '/data/' + fileName); 
     file.pipe(fstream); 
     fstream.on('close', function() { 
      res.end('ok'); 
     }); 
    }); 
}); 

console.log(req.busboy);回報undefined。爲什麼?!??!

+0

是您的'app.use(busboy({immediate:true})); * * before * your routes?另外,你可能不應該設置'immediate:true',尤其是因爲你正在執行'req.pipe(req.busboy)''你自己。 – mscdex 2014-09-23 12:49:26

+0

是的。即使沒有'''immediate:true'',結果也是一樣。 – 2014-09-23 12:53:11

回答

3

排序了!事實證明,在contentTypeform/multi-part,這是不是這種情況

+3

你能更具體嗎?內容類型是什麼? – Jordan 2015-07-22 18:58:13

1

對於多部分形式:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary63SFlxFGGDbxCqT7 

邊界是隨機生成所以爲了得到這個在節點快遞工作是建議將此標頭設置爲「未定義」,瀏覽器將負責其餘部分。例如:

$http({ 
     method: 'POST', 
     url: 'http://youurl.com, 
     data: data, 
     // Remove the 'Content-Type' header for multipart form submission 
     headers: { 'Content-Type': undefined }, 
    }).then(function successCallback(response) { 
     // this callback will be called asynchronously 
     // when the response is available 
    }, function errorCallback(response) { 
     // called asynchronously if an error occurs 
    }); 

對於任何人有同樣的問題,作爲喬丹:

「你能更具體什麼內容類型?」

這意味着在從瀏覽器發送到Web服務器的請求中設置'Content-Type'標頭。例如,將內容類型標題設置爲JSON,如下所示:

Content-Type: application/json; charset=utf-8