How to delete a file image on amazon s3 when
Asked Answered
C

4

7

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");
 }
});
Crucifer answered 3/12, 2020 at 11:9 Comment(0)
R
8

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);
});
Ricebird answered 3/12, 2020 at 11:49 Comment(0)
R
1

I had exactly the same problem which is "that the file(image) still exists on my Aws s3 console" it could be because of passing image location instead of image name When uploading the image to aws here is the respone

{
  fieldname: 'name',
  originalname: 'apple.png',
  encoding: '7bit',
  mimetype: 'image/png',
  size: 59654,
  bucket: 'my-bucket-name',
key: 'apple-1426277135446.png', //=> what i needed to pass as(key)
  acl: 'public-read',
contentType: 'application/octet-stream',
contentDisposition: null,
storageClass: 'STANDARD',
serverSideEncryption: null,
metadata: null,
location: 'https://my-bucket-name.Xx.xu-eXst-3.amazonaws.com/apple-
1426277135446.png', // => this is what i was passing to deleteObject as "key" 
etag: '"CXXFE*#&SHFLSKKSXX"',
versionId: undefined
 }

my problem was that i was passing the image location instead of the image name in deleteObject function

s3.deleteObject({ Bucket: 'bucket-name', Key: 'image.jpg' }, (err, data) 
 // key in the argument has to be the filename with extension without 

// URL like:  https://my-bucket-name.s3.ff-North-1.amazonaws.com/

  => {
    console.error(err);
    console.log(data);
});

so eventually i could extract the name of the file(image) with extension and passed to the function above here is what i used the function from this answer answer

function parseUrlFilename(url, defaultFilename = null) {
// 'https://my-bucket-name.Xx.xu-eXst-3.amazonaws.com/apple-
1426277135446.png'
let filename = new URL(url, 
"https://example.com").href.split("#").shift().split("?").shift().split("/").pop(); //No need to change "https://example.com"; it's only present to allow for processing relative URLs.
if(!filename) {
    if(defaultFilename) {
        filename = defaultFilename;
    //No default filename provided; use a pseudorandom string.
    } else {
        filename = Math.random().toString(36).substr(2, 10);
    }
}
    // resulting apple-1426277135446.png'
    return filename;
}
Rheingold answered 14/7, 2021 at 16:21 Comment(0)
I
1

I had exactly the same problem and fixed by given code,

  s3.deleteObjects(
    {
      Bucket: 'uploads-images',
      Delete: {
        Objects: [{ Key: 'product-images/slider-image.jpg' }],
        Quiet: false,
      },
    },
    function (err, data) {
      if (err) console.log('err ==>', err);
      console.log('delete successfully', data);
      return res.status(200).json(data);
    }
  );

This works exactly for me.

Indivertible answered 23/7, 2021 at 15:25 Comment(0)
M
1

Example of file deletion from url (file location) on amazone server This code allows you to have the fileKey from the url Before you need install urldecode

npm i urldecode

public async deleteFile(location: string) {
    let fileKey = decoder(location)
    const datas = fileKey.split('amazonaws.com/')
    fileKey = datas.pop();
    const params = {
      Bucket: 'Your Bucket',
      Key: fileKey,
    };
    await this.AWS_S3.deleteObject(params).promise();
  }
Masterly answered 18/11, 2021 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.