Error handling when uploading file using multer with expressjs Error handling when uploading file using multer with expressjs express express

Error handling when uploading file using multer with expressjs


This is how to write multer middleware that handle upload and errors

const multer = require("multer");function uploadFile(req, res, next) {    const upload = multer().single('yourFileNameHere');    upload(req, res, function (err) {        if (err instanceof multer.MulterError) {            // A Multer error occurred when uploading.        } else if (err) {            // An unknown error occurred when uploading.        }        // Everything went fine.         next()    })}


You can handle errors using the onError option:

app.post('/upload',[  multer({    dest    : './uploads/',    onError : function(err, next) {      console.log('error', err);      next(err);    }  }),  function(req, res) {    res.status(204).end();  }]);

If you call next(err), your route handler (generating the 204) will be skipped and the error will be handled by Express.

I think (not 100% sure as it depends on how multer is implemented) that your route handler will be called when the file is saved. You can use onFileUploadComplete to log a message when the upload is done, and compare that to when your route handler is called.

Looking at the code, multer calls the next middleware/route handler when the file has been uploaded completely.


Try this

var upload = multer().single('avatar')app.post('/profile', function (req, res) {  upload(req, res, function (err) {    if (err) {      // An error occurred when uploading       return    }    // Everything went fine   })}

ref :

http://wiki.workassis.com/nodejs-express-get-post-multipart-request-handling-example/

https://www.npmjs.com/package/multer#error-handling