6

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 2

11

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)
}
1
  • It solved my issue.The file size limit is handled. Dec 6, 2021 at 7:02
0

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
};
2
  • how to send this 'Error' as an API response Dec 5, 2020 at 12:19
  • Hi Mohammad, do you have your service working with HTTP and image uploads via multipart form data?
    – MoonKnight
    Aug 24, 2022 at 15:21

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.