Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to upload a file to my node js server using express. Here is my nodejs code:

var express=require('express');
var app=express();
var fs=require('fs');
var sys=require('sys');
app.listen(8080);
app.get('/',function(req,res){
fs.readFile('upload.html',function (err, data){
    res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
    res.write(data);
    res.end();
});



});
app.post('/upload',function(req,res)
{
console.log(req.files);
fs.readFile(req.files.displayImage.path, function (err, data) {
  // ...
  var newPath = __dirname;
  fs.writeFile(newPath, data, function (err) {
    res.redirect("back");
  });
});

});

My upload.html file:

<html>
<head>
<title>Upload Example</title>
</head>
<body>

<form id="uploadForm"
      enctype="multipart/form-data"
      action="/upload"
      method="post">
  <input type="file" id="userPhotoInput" name="displayImage" />
  <input type="submit" value="Submit">
</form>

<span id="status" />
<img id="uploadedImage" />


</body>
</html>

I am getting an error that the req.files is undefined. What could be wrong? The file upload is also not working.

share|improve this question

1 Answer

up vote 1 down vote accepted

As noted in the docs, req.files, along with req.body are provided by the bodyParser middleware. You can add the middleware like this:

app.use(express.bodyParser());

// or, as `req.files` is only provided by the multipart middleware, you could 
// add just that if you're not concerned with parsing non-multipart uploads, 
// like:
app.use(express.multipart());
share|improve this answer
 
Thanks very much. I shouldn't have missed that. –  Shubham Tripathi Jun 20 at 16:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.