Skip to content

Instantly share code, notes, and snippets.

@huynhsamha
Created March 17, 2020 15:36
Show Gist options
  • Save huynhsamha/348722d47ee457454688698ff77fee1a to your computer and use it in GitHub Desktop.
Save huynhsamha/348722d47ee457454688698ff77fee1a to your computer and use it in GitHub Desktop.
Example for multer upload custom error handling
const express = require('express')
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'tmp')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
return cb(new Error('Invalid mime type'));
}
}
});
const uploadSingleImage = upload.single('image');
app.post('/upload', function (req, res) {
uploadSingleImage(req, res, function (err) {
if (err) {
return res.status(400).send({ message: err.message })
}
// Everything went fine.
const file = req.file;
res.status(200).send({
filename: file.filename,
mimetype: file.mimetype,
originalname: file.originalname,
size: file.size,
fieldname: file.fieldname
})
})
})
app.listen(3000, () => {
console.log("Server is listening on port: 3000");
});
@zotizzmoy
Copy link

My multer function is in middleware, How to put error in the controller?

@hryashik
Copy link

My multer function is in middleware, How to put error in the controller?

Just return callback with error in fileFilter:

const upload = multer({
   dest: "uploads",
   fileFilter(req, file, callback) {
      if (encodeURI(file.originalname).length > 30) {
         // You can throw any error or MulterError(code)
         return callback(new CustomHttpError("File name must contain no more 30 symbols", 413));
      }
      callback(null, true);
   },
});

You can read more about error codes and their processing here - https://github.com/expressjs/multer#filefilter

@Joshua-Nweze
Copy link

Thanks man, you're a life saver

@nacza
Copy link

nacza commented Dec 14, 2023

Hello , why my app is hang when i hit the endpoint twice, if you try on postman, it will hang with "Sending request..." message

This is my code :

R_menu.js

const MW_MULTER = [handlerUploadImage];
router.post("/upload-image", MW_MULTER, C_menu.uploadImage);

MW_menu.js

const handlerUploadImage = (req, res) => {
  console.log("Handler Upload Image middleware reached");

  const h = upload.single("image");
  h(req, res, function (err) {
    if (err) {
      return res.status(400).send({ message: err.message });
    }
  });
};

@hryashik
Copy link

Hello , why my app is hang when i hit the endpoint twice, if you try on postman, it will hang with "Sending request..." message

This is my code :

R_menu.js

const MW_MULTER = [handlerUploadImage];
router.post("/upload-image", MW_MULTER, C_menu.uploadImage);

MW_menu.js

const handlerUploadImage = (req, res) => {
  console.log("Handler Upload Image middleware reached");

  const h = upload.single("image");
  h(req, res, function (err) {
    if (err) {
      return res.status(400).send({ message: err.message });
    }
  });
};

Every middleware should call next handler or throw error (or smth). Your handlerUploadImage takes 3 parameters: req, res and next. Call next() in your handler, and request will be transferred into C_menu.uploadImage

@codal-umistri
Copy link

codal-umistri commented Mar 12, 2024

"Hello @nacza,

I've encountered an issue while uploading '.png' files and it seems you're facing the same problem. Could you please review my code on GitHub (https://github.com/codal-umistri/Multer).

It will help You!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment