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

João Menighin picture João Menighin · Jul 19, 2015 · Viewed 47k times · Source

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.

Answer

Rubén Marrero picture Rubén Marrero · Jul 28, 2015

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.