Skip to content
Advertisement

How to validate multiple file uploads with multer expressjs

I have a problem with express.js and multer when I try to upload 2 valid images and 1 example pdf to validate is all images, it will upload that two images into a folder, and then it will throw the error for pdf that is an invalid format, can I somehow validate first all images and then do the upload to folder or throw the error is something is wrong here is my code

const fileStorageEngine = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './images');
    },
    filename: (req, file, cb) => {
        cb(null, Date.now()+ '--' +file.originalname);
    }
});
    
const fileFilter = (req, file, cb) => {
    // Reject a file
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
        cb(null, true);
    } else {
        req.fileValidationError = 'File type not supported';
        cb(null, false);
    }
};
    
const upload = multer({
    storage: fileStorageEngine,
    limits: {
        fileSize: 1024 * 1024 * 5 // Accept files to 5mb only
    }, 
    fileFilter: fileFilter
});
app.post('/multiple', upload.array('images', 3), async(req, res, next) => {
    try {
        console.log("POST Multiple Files: ", req.files);

        if (await req.fileValidationError) {
            throw new Error(req.fileValidationError);
        } else {
            for (let i = 0; i < req.files.length; i++) {
                let storeImage = await StoreImages.create({
                    images: req.files[i].path
                });
        
                if (!storeImage) {
                    throw new Error('Sorry, something went wrong while trying to upload the image!');
                }
            }
            res.status = 200;
            res.render("index", {
                success: true,
                message: "Your images successfully stored!"
            });
        }
    } catch(err) {
        console.log("POST Multiple Error: ", err);

        res.status = 406;
        return res.render('index', {
            error: true,
            message: err.message
        })
    }
});

I want to validate all uploaded files before insert to a folder, server, etc…

Advertisement

Answer

I found a solution by throwing the error in cb function in fileFilter function

const fileFilter = (req, file, cb) => {
    // Reject a file
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png'){
        cb(null, true);
    }else{
        cb(new Error('File type not supported'));
    }
};
Advertisement