In express 4.1.3 I try to process a POST request from a form with the parameter enctype='multipart/form-data' . For processing I used various modules of the type (multer, connec-busboy), but I could not understand how to use them.

Tell me the best way to upload files in express 4?

Here is a link to a bitbucket where you can see the code.

when the node bin/wwww is launched, an exception is node bin/wwww to the console and the server crashes.

 throw new TypeError('app.use() requires middleware functions'); ^ TypeError: app.use() requires middleware functions 

I’ve registered only one setting for the multar when I’m cleaning the server again.

 app.use(multer({ dest:'./public/upload' })); 

Thank!

  • Can you give a minimal example of code that does not work? And then the link is too much that is not relevant to the question. - Dmitriy Simushev
  • tried to clarify. - VasilyGuzov

1 answer 1

Created an upload object on the basis of the multer object and passed it in the dest parameter where to upload the downloaded files

 var multer = require('multer'); var upload = multer({ dest:'./public/upload/' }); 

After that, the app.post method added an upload object, called the fields method and passed an object with a description of the form fields to it in an array.

 app.post('/upload', upload.fields([{name: 'name'}, {name: 'someImage', maxCount: 1}]), image.submit(app.get('uploadDir'))); 

The image.submit function, which processes this route in the routes/images file, receives the file via req.files.someImage[0] , creates a directory from the req.body.name parameter and stores the downloaded file into it.

  exports.submit = function (dir) { return function (req, res, next) { var img = req.files.someImage[0]; console.log(img.originalname); var name = req.body.name || img.name; var actorDir = name; var path = join(dir, actorDir); fs.mkdir(path, function (err) { if (err) return next(err); var newPath = path + '/' + img.originalname; fs.rename(img.path, newPath, function (err) { if (err) return next(err); Photo.create({ name: name, path: img.name }, function (err) { if (err) return next(err); res.redirect('/'); }); }); }) }; };