Is it possible to integrate the express-Validator with the multer?

Asked

Viewed 35 times

1

I am developing an API for study and in this API I have the functionality to add a vehicle, in which I recover the data passed by the user and an image. But as I am using the express-Validator, every time it presents a validation error, the image upload happens the same way. I wonder if it is possible to add a condition or something of the kind so that the upload is performed only when no validation error occurs.

I’m using the express-Validator for the validation of the data and the ladies as middleware for uploading images.

Excerpt from the code I would like to know if it is possible to add a condition to the upload:

// Adiciona um novo veiculo
app.post("/AdicionarVeiculo", [upload.single("image"), regrasValidacao], (req, res) => {

  // Guarda os erros de validação
  const validationErros = validationResult(req);

  // Verifica se ocorreu algum erro
  if (!validationErros.isEmpty()) {
    return res.status(400).json({
      errors: validationErros.array()
    });
  }

  const dados = { ...req.body,
    imagem: req.file.path
  };

  console.log(dados);

  Veiculos.adicionarVeiculo(dados, res);
});
  • 1

    Unfortunately there is no decent way to validate before uploading with ladies. It even offers a method fileFilter for file type checking, but to validate other fields would exaggerate the purpose of this function. Your problem is more focused on uploading in case of error, it may suggest an alternative as deleting the file in case of validation error?

  • Well thought out, I did it by deleting the image I just uploaded in case any validation error occurs and it worked! thank you very much!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.