Search code examples
node.jsexpressmulter-s3

How to delete a file image on amazon s3 when


I have a program Model, and i the program has an image attribute which I use multers3 to upload when creating the Program.

The challenge that I am facing now is that, when I delete the program, everything gets deleted on my local machine but I realized that the file(image) still exists on my Aws s3 console. How do I get the file deleted both on my database and on Amazon s3?

Here are my Program routes

This is how I delete my Program

router.delete("/:id/delete", function (req, res) {
  const ObjectId = mongoose.Types.ObjectId;
  let query = { _id: new ObjectId(req.params.id) };

   Program.deleteOne(query, function (err) {
    if (err) {
       console.log(err);
     }
    res.send("Success");
  });
});

and this is how i creates my program.

  router.post("/create", upload.single("cover"), async (req, res, next) => {
    const fileName = req.file != null ? req.file.filename : null;
    const program = new Program({
      programtype: req.body.programtype,
      title: req.body.title,
      description: req.body.description,
      programImage: req.file.location,
   });
 try {
   console.log(program);
   const programs = await program.save();
   res.redirect("/programs");
  } catch {
   if (program.programImage != null) {
    removeprogramImage(program.programImage);
  }
  res.render("programs/new");
 }
});

Solution

  • Looking through the Multer-s3 repo, I can't find anything which mentions deleting from s3. There is this function in the source code, but, I can't figure out how to use it.

    You could try using the AWS SDK directly via deleteObject:

    const s3 = new aws.S3({
        accessKeyId: 'access-key-id',
        secretAccessKey: 'access-key',
        Bucket: 'bucket-name',
    });
    
    s3.deleteObject({ Bucket: 'bucket-name', Key: 'image.jpg' }, (err, data) => {
        console.error(err);
        console.log(data);
    });