4

I want to upload a file using angular-file-upload. But when I try to access req.body.files or req.files i get undefined.

Can anybody tell me how to get the file which is uploaded through angular-file-upload in node.js express app ?

Request Payload is as below:

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

JS Code:

$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");
},
2
  • please provide some of your code examples, particularly server side node.js code Commented Jul 7, 2014 at 12:53
  • As i have already mentioned req.files is undefined Commented Jul 7, 2014 at 13:02

2 Answers 2

8

You need to use a middleware that parses files from a request in 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. When a request comes in, it is passed off to the first middleware function, along with a wrapped ServerResponse object and a next callback. 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().

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.

Of course you need to install it first: 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

Sign up to request clarification or add additional context in comments.

5 Comments

express.multipart is gone in Express 4+
So is express.bodyParser. See here.
It throws me a error Most middleware are not bundled with express
Ok, right, I have updated again. I never worked with express 4 for now (which seems to be very new)
I figured out that the app structure i copied from somewhere was using json body parser so i removed json body parser and it worked
-4

Access it in the files object with the name attribute as the key:

req.files.myFile

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.