Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

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

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
ode_modulesexpresslibapplication
.js:209:11)

Im using NodeJS 0.12.7 and Express 4.13.1

How can I achieve that upload? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...