I am trying to build a Node.js Application in Express.js 4 that uploads an image. I decided to use the multer module but cannot access the uploaded file through req.files.
Here Is the code I am using. I restricted it to those parts that I believe are relevant.
Jade code:
form(method="POST", action="createPost", enctype="multipart/form-data")
input(type="file", name="photo")
br
input(type="submit" value="upload")
in routes/admin.js:
var express = require('express');
var multer = require('multer');
var router = express.Router();
var upload = multer({dest: './uploads/'});
router.post('/createPost', upload.single('photo'), function(req, res, next) {
console.log('files:', req.files);
console.log('body:', req.body);
// more code
}
output:
files: undefined
body: {}
The file is stored in the uploads folder but I cannot access its information in req.files. Can anyone help me?
When using upload.single(), per the multer documentation, the resulting file should be in req.file, not req.files. See the example in their doc here.
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
And, here's the actual doc for upload.single():
.single(fieldname)
Accept a single file with the name fieldname. The single file will be stored in req.file.
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