简体   繁体   English

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

[英]How to get uploaded file in Node.js Express app using angular-file-upload

I want to upload a file using angular-file-upload. 我想使用angular-file-upload上传文件。 But when I try to access req.body.files or req.files i get undefined . 但是当我尝试访问req.body.filesreq.files我得到了undefined

Can anybody tell me how to get the file which is uploaded through angular-file-upload in node.js express app ? 任何人都可以告诉我如何获取通过angular.js express app中的angular-file-upload上传的文件?

Request Payload is as below: 请求有效负载如下:

Content-Disposition: form-data; name="myFile"; filename="BroadcomLogo.gif"
Content-Type: image/gif

JS Code: JS代码:

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

Node Code 节点代码

upload: function(req, res) {
    console.log(req.files);
    res.send("Hello");
},

You need to use a middleware that parses files from a request in Node.js: 您需要使用一个中间件来解析Node.js中的请求中的文件:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload', multipartMiddleware,upload);

Simply put, middleware are functions that handle requests . 简而言之, 中间件是处理请求的函数 A server created by connect.createServer can have a stack of middleware associated with it. connect.createServer创建的服务器可以有一堆与之关联的中间件。 When a request comes in, it is passed off to the first middleware function, along with a wrapped ServerResponse object and a next callback. 当请求进入时,它会被传递给第一个中间件函数,以及一个包装的ServerResponse对象和下一个回调。 Each middleware can decide to respond by calling methods on the response object, and/or pass the request off to the next layer in the stack by calling next() . 每个中间件都可以决定通过调用响应对象上的方法来响应,和/或通过调用next()将请求传递给堆栈中的下一层

http://stephensugden.com/middleware_guide/ http://stephensugden.com/middleware_guide/

In the case of the multipart middleware, it will call the next() method so you can write your own function to respond to the request. 对于多部分中间件,它将调用next()方法,以便您可以编写自己的函数来响应请求。

Of course you need to install it first: npm install connect-multiparty 当然你需要先安装它: npm install connect-multiparty

They are other middlewares that handle multipart uploads: 它们是处理分段上传的其他中间件:

You should probably use one that is compatible with connect, as express is built on top of connect 你应该使用一个与connect兼容的,因为express是建立在connect之上的

使用name属性作为键在files对象中访问它:

req.files.myFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM