2

In my app the user has a page on his profile where he can upload images. In order to achieve that I made a Model of an image that, among others, has the name, url(on disk), and the mimitype of the image that is uploaded. Every time I upload an image, an instance of that Model is created, which saves that data to mongo. The image itself gets saved to a folder on my project. In order to disply the uploaded images on the user's page, I assign to every image, the corresponding path on disk. And it works. Then I can also delete images, from te ui and from the database. And it works. The problem is that the images don't get deleted from disk.

This is what I tried so far, in the controller for deleting images route, I added that fs.unlink method, but it doesn't work.

exports.deletePhoto = (req, res) => {
    User.findById(req.params.userid)
        .exec((error, user) => {
            if (error) {
                return  res.json(error);
            }

            Photo.findByIdAndDelete(req.body.photoId)
                .exec((error, photo) => {
                    if (error) {
                        return res.json(error);
                    }

                    **fs.unlink(photo.photo.photoUrl, error => {
                        if (error) {
                            console.log(error);
                            return;
                        }
                    });**

                    user.photos.pull(photo);
                    user.save();

                    return res.status(204).json({
                        message: `Photo successfuly deleted`,
                        photoId: photo._id,
                        photoUrl: photo.photo.photoUrl,
                    });
                });
            });
};

How to delete an image from disk when I delete the image from database? Basically, when I delete an image from the UI, I want it to be deleted from the disk as well.

Multer config:

const FILE_PATH = 'uploads';
const storage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, FILE_PATH),
    filename: (req, file, cb) => {
        cb(null, `${Date.now()}_${file.originalname}`)
    },
});

const fileFilter = (req, file, cb) => {
    if (!file.filename.match(/\.(jpeg|jpg|png)$/)) {
        console.log('Only upload jpg and png files.');
    }

    cb(undefined, true);
}

The route to delete image:

router.post('/upload/:userid', multer({ storage }).single('photo'), uploadPhoto);
code_dude
  • 951
  • 2
  • 15
  • 28

0 Answers0