Search code examples
javascriptnode.jsmulter

Multer with Express.js


I am having some issue with using Multer with express.js. So this works fine:

const multer = require('multer');
let upload = multer({dest: 'uploads/'});

app.post('/upload', upload.single('image'), function (req, res, next) {
    console.log(req.file)
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
});

But when I try to do it like this, req.file is undefined:

const multer = require('multer');
let upload = multer({dest: 'uploads/'});
router.route('/', upload.single('image'))
    .post(function (req, res, next) {
        console.log(req.file);
        let memory = new Memory();
        Object.assign(memory, req.body);
        memory.save(function (err) {
            if (err) {
                return res.send(err);
            }
            res.json({message: 'Memory Created', memory});
        });
    })

Just wondering if what the correct syntax would be if I want to seperate my routes.js from my server.js.

I also tried this:

const multer = require('multer');
let upload = multer({dest: 'uploads/'});
router.route('/')
    .post(upload.single('image'), function (req, res, next) {
        console.log(req.file);
        let memory = new Memory();
        Object.assign(memory, req.body);
        memory.save(function (err) {
            if (err) {
                return res.send(err);
            }
            res.json({message: 'Memory Created', memory});
        });
    })

Thanks


Solution

  • Try this:

    router.post('/', upload.single('image'), function (req, res, next) {
        console.log(req.file);
    
        // Do something with the file
    });
    

    Make sure that the post request body has the file attached to the image property. If you are using Postman to test, it should be something like this:

    enter image description here