Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

req.files is undefined when uploading file with multer

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?

like image 809
arne.z Avatar asked Aug 14 '15 00:08

arne.z


1 Answers

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.

like image 168
jfriend00 Avatar answered Oct 13 '22 01:10

jfriend00