2014-09-23 130 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