简体   繁体   中英

Using Multer, how do I delete the previous image file from storage after a user uploaded another image?

I'm a newbie trying to learn Nodejs. I've been trying to resolve an issue using an NPM module called Multer. I can't seem to write the right code to delete a User's image file or overwrite if the user uploads another one. Sorry for the inconvenience. Please help

My Delete Route works perfectly deleting both the "Posts" and "Image". However, my edit Route gives the below error

{"Error":{"errno":-4058,"syscall":"unlink","code":"ENOENT","path":"C:\\cms\\public\\uploads\\image-1568050604308.png"}}

const publicUploads = path.join(__dirname, '../../../public/uploads/');


const storage = 
multer.diskStorage({
destination: publicUploads,
filename(req, file, cb){
    cb(null,`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
}
});

const upload = multer({
storage,
limits: {
    fileSize: 1000000
},
fileFilter(req, file, cb){
    if(!file.originalname.match(/\.(jpeg|jpg|png)$/)){
        return cb(new Error('Please upload an image file'))
    }

    cb(null, true)
}
})

router.put('/admin/posts/edit/:id', upload.single('image'), async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = ['title', 'body', 'status', 'image', 'allowComments'];
const isValid = updates.every(update => allowedUpdates.includes(update));

if(!isValid){
    return res.send({Error: 'Invalid Update'})
}

try {
    const post = await Post.findOne({_id: req.params.id});

    if(!post){
        return res.send({Error: 'Could not find your post'})
    }

    if(req.file){
        fs.unlinkSync(`${publicUploads}${post.image}`);

        post.image = req.file.filename
    }

    updates.forEach(update => {
        post[update] = req.body[update]

    })

    post.allowComments = req.body.allowComments === 'on'? true:false;

    await post.save();
    req.flash('notice', 'Your post was edited successfully!')
    res.status(200).redirect('/admin/posts')
} catch (error) {
    res.send({Error: error})
}
}, (error, req, res, next) => {
res.send({Error: error})
})

You can delete the image natively with the Node package "fs". You don't need to use Multer for this:

  // Remove old photo
  if (oldPhoto) {
    const oldPath = path.join(__dirname, "..", "images", oldPhoto);
    if (fs.existsSync(oldPath)) {
      fs.unlink(oldPath, (err) => {
        if (err) {
          console.error(err);
          return;
        }
        res.status(200).send(userObj);
      });
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM