Upload an array of images with Node.js, Multer and Sharp

Asked

Viewed 499 times

0

In addition to uploading the images I do a treatment on them with Sharp, uploading only 1 image with upload.single('image') the treatment is executed and the image is saved, but when I try an array with upload.array('image', 10) images are saved without receiving the treatment.

The treatment happens in the controller:

async post (req, res) {
const { title, description, locale, resume } = req.body;
const { filename : image } = req.file;
const [name] = image.split('.');
const filename = `${name}.jpg`;
await sharp(req.file.path)
  .resize(600)
  .jpeg({ quality: 80 })
  .toFile(
    path.resolve(req.file.destination, 'obras', filename)
  )

fs.unlinkSync(req.file.path);

const obra = await Obra.create({
  success: true,
  title,
  description,
  resume,
  locale,
  image: filename,
});

return res.json( obra );

},

how to do the same treatment on all images I send?

1 answer

0

the problem was basically in "req.file" which is only used for single uploads, when using array for uploads you need to use "req.files[Indice]". then it was like this:

const arrayImages = []; //Para retorna as imagens no response
let i; //indice
for (i = 0; i<req.files.length; i++) {
  const { filename : image } = req.files[i]; //pegando o nome da imagem
  const [name] = image.split('.');
  let filename = `${name}.jpg`; //mudando pra jpg
  await sharp(req.files[i].path)
    .resize(500) // redimensionando para 500px
    .jpeg({ quality: 80 }) //qualidade para 80%
    .toFile(
      path.resolve(req.files[i].destination, 'obras', filename) //salvando
    )

    arrayImages.push(filename); // adicionando no vetor
  fs.unlinkSync(req.files[i].path); //apagando a imagem original, deixando apenas a imagem tratada salva.
}

Browser other questions tagged

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