如何使用angular-file-upload在Node.js Express应用程序中上传文件

Aja*_*wal 4 node.js express angularjs

我想使用angular-file-upload上传文件.但当我试图访问req.body.filesreq.files我得到undefined.

任何人都可以告诉我如何获取通过angular.js express app中的angular-file-upload上传的文件?

请求有效负载如下:

Content-Disposition: form-data; name="myFile"; filename="BroadcomLogo.gif"
Content-Type: image/gif
Run Code Online (Sandbox Code Playgroud)

JS代码:

$scope.upload[index] = $upload.upload({
   url : '/upload',
   method: 'POST',
   file: $scope.selectedFiles[index],
   fileFormDataName: 'myFile'
});
Run Code Online (Sandbox Code Playgroud)

节点代码

upload: function(req, res) {
    console.log(req.files);
    res.send("Hello");
},
Run Code Online (Sandbox Code Playgroud)

edi*_*999 8

您需要使用一个中间件来解析Node.js中的请求中的文件:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload', multipartMiddleware,upload);
Run Code Online (Sandbox Code Playgroud)

简而言之,中间件是处理请求的函数.connect.createServer创建的服务器可以有一堆与之关联的中间件.当请求进入时,它会被传递给第一个中间件函数,以及一个包装的ServerResponse对象和下一个回调.每个中间件都可以决定通过调用响应对象上的方法来响应,和/或通过调用next()将请求传递给堆栈中的下一层.

http://stephensugden.com/middleware_guide/

对于多部分中间件,它将调用next()方法,以便您可以编写自己的函数来响应请求.

当然你需要先安装它: npm install connect-multiparty

它们是处理分段上传的其他中间件:

你应该使用一个与connect兼容的,因为express是建立在connect之上的