Search code examples
javascriptnode.jsmulter

NodeJS Multer unable to catch eroor


How do I catch the error invoked and return a res status msg? I am unable to catch any error in userController.uploadFile and if I tried to do a upload(req,res (err) in the routes.post, req is not defined.

var storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, url);
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
}).single('file');
let upload = multer({
    storage: storage,
    limits: { fileSize: maxSize },
    fileFilter: (req, file, cb) => {
        console.log(file);
        if (file.mimetype !== 'image/jpeg' || file.mimetype !== 'image/png') {
          return cb(new Error('Only jpeg images allowed'))
        }
    
        cb(null, true)
      }
});

routes.post('/fileupload', upload, userController.uploadFile);

Solution

  • I think we can get this to work with a little tweaking. I've made these changes and tested with a few images.

    Your user controller will look a little different, but something like this should work.

    I've updated to pass any file too large error to the controller, again this will be in the req.uploadError property, so you can handle as you like.

    const userController = { 
        uploadFile(req, res) {
            if (req.uploadError) {
                res.status(400).send("An error occurred - " + req.uploadError.message);
            } else { 
                res.status(201).send("All good");
            }
        }
    }
    
    var storage = multer.diskStorage({
        destination(req, file, cb) {
            cb(null, url);
        },
        filename: function (req, file, cb) {
            cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
        }
    });
    
    let upload = multer({
        storage: storage,
        limits: { fileSize: maxSize },
        fileFilter: (req, file, cb) => {
            console.log(file);
            if (file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
                cb(new Error('Only jpeg or png images allowed'));
            } else {
                cb(null, true);
            }
        }
    }).single('file');
    
    routes.post('/fileupload', (req, res, next) => { 
        upload(req, res, err => {
            req.uploadError = err;
            next();
        })
    }, userController.uploadFile);