Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda