How do I delete the image before it is uploaded using Multer?

Asked

Viewed 130 times

0

I’m having some difficulty with Javascript and Nodejs. I’m new to them. I made an application in React Native and the person can choose to delete their profile image. There are also images in the ads section. I would like to delete the images before uploading the new ones, as the user can choose not to use images in the future. I’m using Multer for uploads and Fs.unlink to delete the images. But I’m not sure where to fit Fs.unlink to delete them before, whether it’s inside the woman herself or have to create a middleware, I have no idea...

const deleteFile = (filePath) => {
fs.unlink(filePath, (error) => {
  if (!error) {
    console.log(false);
  } else {
    console.log('Erro ao deletar arquivo.');
  }
})};

const StoragePerfil = multer.diskStorage({
        destination(req, file, callback) {
            callback(null, './assets/upload/perfil');
        },
        filename: (req, file, callback) => {
            callback(null, `${file.originalname}`)
        },
        });
const uploadPerfil = multer({ storage: StoragePerfil });


app.put('/user/perfil/:id_user', authMiddleware.checkAuth, uploadPerfil.array('photo', 3), perfilController.updatePerfil);

1 answer

0

I have already solved it. I check whether or not the image exists and put in the update function.

const deleteFile = (filePath) => {
fs.unlink(filePath, (error) => {
  if (!error) {
    console.log(false);
  } else {
    console.log('Erro ao deletar arquivo.');
  }
})};


if (typeof req.body.photo === undefined) {         
   funcao.deleteFile(pathfile);       
} 

Thank you.

Browser other questions tagged

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