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.
Multer is a node. js middleware for handling multipart/form-data , which is primarily used for uploading files.
You cannot use Multer without because it's Express middleware.
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.
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) {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With