Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload files use ExpressJS 4? [duplicate]

From ExpressJS 4 API, I find the req.files was invalid. How to upload files use ExpressJS 4 now?

like image 239
vcLwei Avatar asked Apr 28 '14 11:04

vcLwei


2 Answers

I just had this issue after upgrading, where req.files was undefined. I fixed it by using multer.

So,

npm install multer

and then in your app.js

var multer = require('multer');
app.use(multer({ dest: './tmp/'}));

I didn't have to change anything else after that and all my old functionality worked.

like image 57
MikeSmithDev Avatar answered Oct 02 '22 20:10

MikeSmithDev


express.bodyParser is not included in express 4 by default. You must install separately. See https://github.com/expressjs/body-parser

Example :

var bodyParser = require('body-parser');

var app = connect();

app.use(bodyParser());

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next();
})

There is also node-formidable

var form = new formidable.IncomingForm();

form.parse(req, function(err, fields, files) {
  res.writeHead(200, {'content-type': 'text/plain'});
  res.write('received upload:\n\n');
  res.end(util.inspect({fields: fields, files: files}));
});

return;

Here is how I did it:

form = new formidable.IncomingForm();
form.uploadDir = __dirname.getParent() + "/temp/";
form.parse(req, function(err, fields, files) {
  var newfile, path, uid, versionName;
  uid = uuid.v4();
  newfile = __dirname.getParent() + "/uploads/" + uid;
  copyFile(files.file.path, newfile, function(err) {
    if (err) {
      console.log(err);
      req.flash("error", "Oops, something went wrong! (reason: copy)");
      return res.redirect(req.url);
    }
    fs.unlink(files.file.path, function(err) {
      if (err) {
        req.flash("error", "Oops, something went wrong! (reason: deletion)");
        return res.redirect(req.url);
      }
      // done!
      // ...
    });
  });
});
like image 31
Vinz243 Avatar answered Oct 02 '22 21:10

Vinz243