Handle Multer fileSize error when uploading large files

Viewed 2708

I'm uploading files using multer on my server and while uploading using limits: { fileSize: 3000000 } I'm restricting the file size up to 3MB. Now the problem I'm facing is when a larger file is being uploaded I'm getting MulterError: File too large at abortWithCode error and my server is being aborted and crashed. I've tried using if (err instanceof multer.MulterError) { console.log("file too large")} and using upload as middleware to handle the error but it doesn't seem to work and my server keeps crashing when a larger file is uploaded. Any idea how to handle the error case??? I don't want my server to crash and send the error out as a response to the API

Router:

const multer = require("multer");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + file.originalname);
  },
});

const upload = multer({ storage: storage, limits: { fileSize: 2000000 } });

module.exports.setRouter = (app) => {
  app.post("/create", upload.single("imageUrl"), userController.createUser);
}

Controller Function:

let createUser = (req, res) => {
  let newUser = new UserModel({
    name: req.body.name,
    email: req.body.email,
    password: passwordLib.hashpassword(req.body.password),
    imageUrl: req.file.path,
  });

  // saving the new user
  newUser.save((err, result) => {
    if (err) {
      console.log(err);
      res.send(err);
    } else {
      res.send(result);
    }
  });
};

app.js

const express = require("express");
const app = express();
app.use("/uploads", express.static("uploads"));
2 Answers

You can catch the error with an additional error handler that is executed after multer.

const multer = require('multer')
const fileSizeLimitErrorHandler = (err, req, res, next) => {
  if (err) {
    res.send(413)
  } else {
    next()
  }
}

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads')
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname)
  },
})

const upload = multer({ storage: storage, limits: { fileSize: 2000000 } })

module.exports.setRouter = (app) => {
  app.post('/create', upload.single('imageUrl'), fileSizeLimitErrorHandler, userController.createUser)
}

use this

const upload = multer({ storage: storage,
                        limits: { fileSize: 2000000 },
                        fileFilter: function(req, file, cb){
                            checkFileType(file, cb)
                        }
                        });




function checkFileType(file, cb){
    // Allowed ext
    const filetypes = /jpeg|jpg|png/;

    //check ext
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());

    //check mime
    const mimetype = filetypes.test(file.mimetype);

    if(mimetype && extname){
        return cb(null, true);
    }else{
        cb('Error')
    }
}

controller

let createUser = (req, res) => {
    upload(req, res, (err) => {
    if (err) res.send(err);
    })

//the rest (saving new user) here
};
Related