Search code examples
javascriptexpressmulter

Multer Only Reading Undefined


I cannot for the life of me get multer's fileupload working. I've read dozens of tutorials, followed YT guides, and scoured dozens of StackOverflow questions, but cannot get the thing to work through Postman.

This is the route's page, with the route being /image-upload.

Here's the complete code:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const multer = require('multer');

const fileUpload = require('express-fileupload');

let path = require('path');


var storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, __dirname + '../uploads')
    },
    filename: (req, file, cb) => {
      cb(null, file.fieldname + '-' + Date.now())
    }
});

var upload = multer({storage: storage});

router.post('/', upload.single('image'), (req, res, next) => {
    let file = req.file;
    console.log(req.file);
    console.log(req.files);
    if (!file) {
        return res.json({nofile: 'please upload a file'})
    }
})

module.exports = router;

It's not a file size issue, as the file size is 46KB. I get undefined when I console.log(req.file), yet I get the full data details when I do: console.log(req.files). In Postman, it just returns the json error, as if the file isn't even being read by multer. In postman I'm correctly using form-data, to the POST route, and the file field name is: image, like I state in the POST route.


Solution

  • I resolved it! Express-fileupload was the issue. When you use express-fileupload in the file, it reserves req.file. Therefore the Multer middleware cannot access it. By removing that, I was able to fix it and upload it properly.