Req.files in undefined at the server side (built with express & node) when sending files using dropzone

1k Views Asked by At

I am using dropzone to upload files from the UI. Here is my drozone configuration:

 var imageUpload = new Dropzone('div#dataSection', {
        url: 'api/image',
        autoProcessQueue: true,
        paramName: 'file'
      });

I am using node and expressjs to build the server side endpoint based on this link

I am excuting below code on the server side.

fs.readFile(req.files.displayImage.path, function (err, data) {
  // ...
  var newPath = __dirname + "/uploads/uploadedFileName";
  fs.writeFile(newPath, data, function (err) {
    res.redirect("back");
  });
});

The problem is req.files in coming as undefined. Am I missing anything?

1

There are 1 best solutions below

0
On BEST ANSWER

The tutorial you were following is quite outdated, and certainly written for old version of express. With express 4.0, released in April 2014, (almost) all built-in middleware was dropped, including the one parsing uploaded files as req.files.

That's the problem, and the solution is to use separate module to handle uploaded files. Multer seems like a natural choice for that (kudos to @Ben Fortune for this suggestion).

First, install multer Node.js module:

npm install multer

Then, in the code on server side:

var express = require('express')
var multer  = require('multer')

var app = express()
app.use(multer({ dest: './uploads/'})) // directory to store uploaded files in

After that, all POST-ed files should be available as req.files in your route handler functions, in the format of Multer file objects.