Delete file from Amazon s3 using Javascript sdk

01 / Aug / 2015 by Sanchit . 2 comments

Now a days AWS S3 is commonly used as data storage. So there is one common requirement to delete a file or directory from S3. There are plenty of options avaibale to do the same, so we using javascript implementation for this. There are basic two steps by which you can delete a file from S3.

1. Javascript sdk integration:

[java]
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.24.min.js"></script>
<script type="text/javascript">
AWS.config.update({
accessKeyId : ‘YOUR_ACCESS_KEY’,
secretAccessKey : ‘YOUR_SECRET_KEY’
});
AWS.config.region = ‘REGION’; // ex: ap-southeast-1
</script>
[/java]

More on integration : s3 bucket javascript integration

2. Javascript method to delete file.

[java]
function deleteFile() {
var bucketInstance = new AWS.S3();
var params = {
Bucket: ‘BUCKET_NAME’,
Key: ‘FILENAME’
};
bucketInstance.deleteObject(params, function (err, data) {
if (data) {
console.log("File deleted successfully");
}
else {
console.log("Check if you have sufficient permissions : "+err);
}
});
}
[/java]

You can read the full documentation here : s3 Javascript methods documentation

In AWS terminology a file is called as an Object. We just need to call the deleteObject method which takes bucketName and fileName as parameters.

This method will delete the file from s3 and check the response to make sure the file is deleted or not.

To use this library please make sure that you have enabled cros configuration. Also it is not advisable to display your keys directly on page, so you can use Amazon Cognito or web identity federation feature. To know more use the below given link : http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-configuring.html

Hope this will help you 🙂

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Chad

    Do you have any guidance on how to do this S3 File Delete with Angular2? I currently have file upload working. Any help would be much appreciated.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *