Gnanavel
Gnanavel

Reputation: 665

Handling errors in multer?

For error handling multer suggest

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.
  })
})

I wrote a custom middleware for uploading different types of file.

const { check } = require("express-validator")
const multer  = require('multer')
const mime = require('mime-types')

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

const uploadFile = (fieldname,filetypes,fileSize)=>{
    return (req,res,next)=>{
        let file = upload.single(fieldname)
        file(req,res,function(err){
            if (err instanceof multer.MulterError) {
                req.fileError = {
                    param: "image",
                    msg: "Unable to process request"
                }
                return next()
            } else if (filetypes.includes(mime.extension(req.file.mimetype)) === false) {
                req.fileError = {
                    param: "image",
                    msg: `Only ${filetypes.toString()} allowed`
                }                
                return next()
            } else if (req.file.size > fileSize) {
                req.fileError = {
                    param: "image",
                    msg: `File size should not exceed ${formatBytes(req.file.size)}`
                }                
                return next()
            }
        })
    }
}

course_validator = [
    check("name")
    .trim()
    .isLength({min:3,max:100})
    .withMessage("Course name should be between 3 to 100 characters")
]
app.get("/create/post",uploadFile("image",["jpeg","jpg"],122880),(req,res)=>{

    const errors = validationResult(req)
    if(!errors.isEmpty()){
        return res.json({
            status: false,
            error: req.fileError ? [...errors.array(),req.fileError] : errors.array()
        })
    }
})

If there is no error then only I need to upload the file to uploads folder. When I upload a other than jpeg or jpg I am getting error with message that Only jpeg,jpg allowed. This is what I need. But the problem is the file is also getting uploaded to uploads folder.

Upvotes: 0

Views: 526

Answers (1)

Smit Gajera
Smit Gajera

Reputation: 1039

For custom error messages you can go through this controller here I'm checking to file type when uploading an image and in the controller, if there is no file selected at that time I'm sending a custom message with simple if the condition after passing all if image and the products will be saved in DB

exports.postProduct = (req, res, next) => {
  const title = req.body.title;
  const image = req.file;
  const price = req.body.price;
  const description = req.body.description;

 if (!image) {
        return res.status(422).render("admin/add-product", {
          pageTitle: "Add Product",
          path: "/adminproducts",
          hasError: true,
          product: {
            title: title,
            price: price,
            description: description,
          },
          errorMessage: "Atteched file is not an image!!!",
          validationErrors: [],
        });
      }
  const imageUrl = image.path;

  const product = new Product({
    title: title,
    imageUrl: imageUrl,
    price: price,
    description: description,
    userId: req.user,
  });
  product
    .save()
    .then((results) => {
      console.log("Product Created Successfully");
      res.redirect("/admin/products");
    })
    .catch((err) => {
      console.log(err);
    });
};

Upvotes: 1

Related Questions