Vladimir Gabrielyan
Vladimir Gabrielyan

Reputation: 801

Delete image from Amazon S3 Storage

I am trying to delete an image from Amazon S3 Storage, but it doesn't delete.

I am using following code:

var s3 = AWS.S3(awsCredentials);
s3.deleteObject({
  Bucket: MY_BUCKET,
  Key: myKey
},function (err,data){})

but images that I want to delete still persist.

I even used s3.deleteObjects function,it returns deleted object names, but when I checked the storage, the images were still there.

Upvotes: 8

Views: 24842

Answers (3)

Md Abdul Halim Rafi
Md Abdul Halim Rafi

Reputation: 1980

You have to specify the exact your key. For example: If it is in the root directory of the bucket,
then Key: "your key.extension". And, if it is in some other directory like folder/subfolder/filename.extension., then you have to specify this.

const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ID,
  secretAccessKey: process.env.AWS_SECRET,
});

const params = {
    Bucket: process.env.AWS_BUCKET_NAME,
    Key: `folder/subfolder/filename.fileExtension`
};

s3.deleteObject(params, (error, data) => {
  if (error) {
    res.status(500).send(error);
  }
  res.status(200).send("File has been deleted successfully");
});

Upvotes: 0

Raghul SK
Raghul SK

Reputation: 1390

when you send the key dynamically, use local storage to store the key and send it dynamically to delete image

var s3 = AWS.S3(awsCredentials); 
s3.deleteObject({  
 Bucket: MY_BUCKET, 
 Key: 'yourFileKey' 
},function (err,data){})

Upvotes: 3

Piyush Patil
Piyush Patil

Reputation: 14543

You have to use the key in this way and not just the name of the file that is to be deleted then it will work.

var s3 = AWS.S3(awsCredentials);
s3.deleteObject({
  Bucket: MY_BUCKET,
  Key: 'some/subfolders/nameofthefile1.extension'
},function (err,data){})

Upvotes: 21

Related Questions