Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
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...

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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'));
    }
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda