17

I am using multer to save the file on server developed through express & nodejs.

I am usign following code.

var express = require('express'),
    multer  = require('multer')

var app = express()

app.get('/', function(req, res){
  res.send('hello world');
});

app.post('/upload',[ multer({ dest: './uploads/'}), function(req, res){

    res.status(204).end()
}]);

app.listen(3000);

Multer saves the file for me in the specified destination folder.

All this is working fine but I have following questions:

  1. If the file saving fails for various reasons, it looks like my route will always return status 204.
  2. I am not sure if status 204 is retured after file is saved or while the file is getting saved asynchronously, status 204 is returned.
SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • For **2022** it's important to note that **if there's an error multer simply passes along to your normal Express error route**. If for some reason you need to handle it separately, see Arya's code. – Fattie Sep 23 '22 at 13:45

9 Answers9

23

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()
    })
}
Raad Altaie
  • 1,025
  • 1
  • 15
  • 28
14

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381
8

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

Bikesh M
  • 8,163
  • 6
  • 40
  • 52
1

As you can see from the code below (the source from the muter index.js file), if you not pass the onError callback the error will be handled by express.

    fileStream.on('error', function(error) {
      // trigger "file error" event
      if (options.onError) { options.onError(error, next); }
      else next(error);
    });
Viktor Soroka
  • 187
  • 2
  • 4
1

Be careful with the system when the user sends anything to you

I usually set more [*option1]:

process.on('uncaughtException', function(ls){
  // console.log(ls);
  (function(){})();
});

And then:

var upload= multer({ dest: __dirname + '/../uploads/' }).single('photos');
// middle ..
upload(req, res, function (err) {
  if (err instanceof multer.MulterError) {
    // A Multer error occurred when uploading.
    console.log('MulterError', err);
  } else if (err) {
    // An unknown error occurred when uploading.
    // Work best when have [*option1]
    console.log('UnhandledError', err);
  }
  if(err) {
    return res.sendStatus(403);
  }
  res.sendStatus(200);
});

package: "multer": "^1.4.2"

Diep Gepa
  • 515
  • 5
  • 5
1
    var multer = require('multer')
    var upload = multer().single('avatar')
     
    app.post('/profile', function (req, res) {
      upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
          handle error
        } else if (err) {
          handle error
        }
        else{
          write you code
        }
      })
    })

you can see this from the documentation

turivishal
  • 34,368
  • 7
  • 36
  • 59
Arya Anish
  • 578
  • 1
  • 7
  • 18
0

According to the multer documentation (https://github.com/expressjs/multer#error-handling)

Error handling

When encountering an error, Multer will delegate the error to Express. You can display a nice error page using the standard express way.

If you want to catch errors specifically from Multer, you can call the middleware function by yourself. Also, if you want to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError).

code sample

   const multer = require('multer')
   const upload = multer().single('avatar')
   
   app.post('/profile', function (req, res) {
     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.
     })
   })

When we re-write the code in this question with latest version of multer (v1.4.5-lts.1)

const express = require('express');

const multer = require('multer');

const app = express();

const upload = multer({ dest: './uploads/' }).single('fieldName');

app.get('/', (req, res) => {
    res.send('hello world');
});

app.post(
    '/upload',
    (req, res, next) => {
        upload(req, res, (err) => {
            if (err instanceof multer.MulterError) {
                res.status(404).send(err + 'Upload failed due to multer error');
            } else if (err) {
                res.status(404).send(err + 'Upload failed due to unknown error');
            }
            // Everything went fine.
            next();
        });
    },
    (req, res) => {
        res.status(204).end();
    }
);

app.listen(3000);

To check the Multer errors and non multer errors we can add validations using fileFilter and limits eg: I am adding a CSV file filter method and some limits

// CSV file filter - will only accept files with .csv extension
const csvFilter = (req, file, cb) => {
    console.log('csv filter working');
    if (file.mimetype.includes('csv')) {
        cb(null, true);
    } else {
        cb('Please upload only csv file.', false);
    }
};

// adding the csv file checking, file number limit to 1 and file size limit 10 1kb
const upload = multer({
    dest: './uploads/',
    fileFilter: csvFilter,
    limits: { files: 1, fileSize: 1024 } 
}).single('fieldName');

We can see different errors are thrown when we try to upload non CSV file or >1kb sized file or multiple files.

Jifri Valanchery
  • 189
  • 5
  • 15
0

I know its late but it might help others.

Here is how I handle errors and use it safely in my express/typescript project.

const upload = (fieldName: string) => {
  return (req: Request, res: Response, next: NextFunction) => {
    return multer({
      storage: multer.diskStorage({
        destination: (req, file, cb) => {
          if (file.fieldname === 'post') {
            return cb(null, `${path.join(path.dirname(__dirname), 'uploads/postImg')}`);
          } else if (file.fieldname === 'profile') {
            return cb(null, `${path.join(path.dirname(__dirname), 'uploads/ProfilePic')}`);
          } else {
            return cb(new Error(`${file.fieldname} is incorrect`), null);
          }
        },
        filename: (req, file, cb) => {
          return cb(null, `${file.originalname}-${Date.now()}-${file.fieldname}`);
        },
      }),
      fileFilter: (req, file, cb) => {
        const fileExtension = file.mimetype.split('/')[1];
        if (!(fileExtension in allowedFiles)) return cb(null, false);
        return cb(null, true);
      },
      dest: `${path.join(path.dirname(__dirname), 'uploads')}`,
      limits: {
        fileSize: 1024 * 1024 * 3, // 3MB
        files: 1,
      },
    }).single(fieldName)(req, res, (err: any) => {
      if (err instanceof multer.MulterError) {
        // handle file size error
        if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).send({ error: err.message });
        // handle unexpected file error
        if (err.code === 'LIMIT_UNEXPECTED_FILE') return res.status(400).send({ error: err.message });
        // handle unexpected field key error
        if (err.code === 'LIMIT_FIELD_KEY') return res.status(400).send({ error: err.message });
      }
      next();
    });
  };
};




app.post("/upload", (req: Request, res:Response)=>{
res.json({message:"file uploaded"})
})
Kashif Ali
  • 187
  • 2
  • 9
0

I think the best way is handling error with middleware.

const multerErrorHandling = (err, req, res, next) => {
if (err instanceof multer.MulterError) {
  res.status(400).send("Multer error: " + err.message);
} else {
  next();
}
};
  // you should use after multer to send another respond.
  app.post("/upload", singleUpload,multerErrorHandling,(req, res) => {