How do I delete an object on AWS S3 using Javascript?

前端 未结 5 1269
予麋鹿
予麋鹿 2020-12-13 17:22

I want to delete a file from Amazon S3 using Javascript. I have already uploaded the file using Javascript. Any ideas?

5条回答
  •  Happy的楠姐
    2020-12-13 18:13

    Before deleting the file you have to check the 1) file whether it is in the bucket because If the file is not available in the bucket and using deleteObject API this doesn't throw any error 2)CORS Configuration of the bucket. By using headObject API gives the file status in the bucket.

    AWS.config.update({
            accessKeyId: "*****",
            secretAccessKey: "****",
            region: region,
            version: "****"
        });
    const s3 = new AWS.S3();
    
    const params = {
            Bucket: s3BucketName,
            Key: "filename" //if any sub folder-> path/of/the/folder.ext
    }
    try {
        await s3.headObject(params).promise()
        console.log("File Found in S3")
        try {
            await s3.deleteObject(params).promise()
            console.log("file deleted Successfully")
        }
        catch (err) {
             console.log("ERROR in file Deleting : " + JSON.stringify(err))
        }
    } catch (err) {
            console.log("File not Found ERROR : " + err.code)
    }
    

    As params are constant, the best way to use it with const. If the file is not found in the s3 it throws the error NotFound : null.

    If you want to apply any operations in the bucket, you have to change the permissions of CORS Configuration in the respective bucket in the AWS. For changing permissions Bucket->permission->CORS Configuration and Add this code.

    
    
        *
        PUT
        POST
        DELETE
        GET
        HEAD
        *
    
    
    

    for more information about CROS Configuration : https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html

提交回复
热议问题