Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot app.use(multer). "requires middleware function" error

Tags:

node.js

multer

I'm just starting learning NodeJS and I am stuck with a problem. I would like to upload files to my server. To do so I searched and found out this module multer. Doing as the example on GitHub works:

var express = require('express'); var multer = require('multer'); var upload = multer({ dest: 'uploads/' });  var app = express()  app.post('/uploadImage', upload.single('image'), function(req, res) {     console.log(req.file); }); 

On posting an image with FormData to /uploadImage the image is saved in the uploads/ directory. The thing is the image is saved with a strange name and I would like to save it with its original name. To do so I understood that I would have to call app.use(multer({ dest: 'uploads/' }))' and then I would be able to access req.file in my function like:

app.post('/uploadImage', function(req, res) {     console.log(req.file); }); 

But I get an error on trying app.use():

TypeError: app.use() requires middleware functions     at EventEmitter.use (project\node_modules\express\lib\application .js:209:11) 

Im using NodeJS 0.12.7 and Express 4.13.1

How can I achieve that upload? Thanks.

like image 273
João Menighin Avatar asked Jul 18 '15 22:07

João Menighin


People also ask

Is multer a middleware function?

Multer is a node. js middleware for handling multipart/form-data , which is primarily used for uploading files.

Can I use multer without express?

You cannot use Multer without because it's Express middleware.

How do I upload a node js file to multer?

The following code will go in the app.const multer = require('multer'); const upload = multer({dest:'uploads/'}). single("demo_image"); Here, we have called the multer() method. It accepts an options object, with dest property, which tells Multer where to upload the files.

What is storage in multer?

The disk storage engine gives you full control of storing files to disk.we will create a storage object using: var storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, './upload'); }, filename: function (req, file, cb) {


1 Answers

You need to use app.use(multer({dest:'./uploads/'})) in the form of one of these:

app.use(multer({dest:'./uploads/'}).single(...)); app.use(multer({dest:'./uploads/'}).array(...)); app.use(multer({dest:'./uploads/'}).fields(...)); 

ie:

app.use(multer({dest:'./uploads/'}).single('photo')); 

And be sure to have something like:

<form action="/postPhotos" enctype="multipart/form-data" method="post">     <input type="file" name="photo">     <input type="submit" value="Upload photo"> </form> 

In your html.

like image 101
Rubén Marrero Avatar answered Sep 17 '22 23:09

Rubén Marrero