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"));