multer file validations not working correctly (not recieving responses)

15 views Asked by At

I am creating an image upload feature using multer. It is a multiple image file upload feature. For this, I want two validations on every image file : 1. it should be less than 5mb of size 2. it should be of image/jpeg type. When validations fail, I want to send some json in response that includes the errors The endpoint works fine in the following cases :

  1. when the file is image/jpeg and it is less than 5mb - file uploads without any error
  2. when the file is of any other mimetype but less than 5mb - error is returned
  3. when the file is image/jpeg but greater than 5mb - error is returned BUT, when the file is another mimetype and simultaneously greater than 5mb, the request keeps on pending and after a while, nothing is returned.

here is the code : // controller.js

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/images/');
    },
    filename: function (req, file, cb) {
        cb(null, "image-" + Date.now() + '-' + uuidv4() + "-" + file.originalname);
    }
});
const upload = multer({
    storage: storage,
    limits: { fileSize: 5 * 1024 * 1024 }, // 5MB file size limit
    fileFilter: (req, file, cb) => {
        console.log(file)
        if (file.mimetype === 'image/jpeg') {
            cb(null, true);
        } else {
            cb(new Error('File must be a JPEG image'));
        }
    }
}).array('images', 5);

export const uploadImage = async (req, res) => {
    upload(req, res, (err) => {
        if (err instanceof multer.MulterError) {
            // Multer error
            res.status(400).json({ error: 'Multer error', message: err.message });
        } else if (err) {
            // Other errors
            res.status(500).json({ error: 'Internal server error', message: err.message });
        } else {
            // No errors, proceed to controller
            res.json({ rec: true })
        }
    });

// route.js

import express from 'express'
import { uploadImage} from '../controllers/controller.js';

const imageRouter= express.Router();

imageRouter
    .post('/', uploadImage)

export default imageRouter

I just need to show the user error message according to the validations on the file.

I tried using multer as a middleware but I wasn't able to send the error messages, the messages were being shown in the terminal of node js however. Then I tried by calling upload inside the controller function, which is what the current scenario is.

0

There are 0 answers