How to delete file immediately from AWS S3 bucket after upload images

Viewed 37

there is an issue when I delete file from AWS S3 bucket.

my process is

  1. Upload image files by using multer module
  2. If error is thrown, delete object function goes on
  3. delete images from s3 bucket

The problem arises from step 3. Externally there is no issue on log but actually files was not deleted from s3.

Here's my code

// express routing
app.route('/editPost').patch(jwtMiddleware, uploadImage.array('image', 10), feed.patchFeed);

// delete object function (AWS S3)
// this code is included in patchFeed controller
const deleteImage = async function delete_file(fileName)  {
    let params = {
        Bucket: secret.aws.bucket,
        Key: `feed/${fileName}`
    };
    
    try {
        await s3.deleteObject(params, async function (error, data) {
            if (error) {
                console.log('Delete S3 Object error: ', error.stack);
            } else {
                console.log(data);
                console.log(fileName, " delete success");
            }
        });
        // return await s3.deleteObject(params).promise();
    } catch(error) {
        console.log(error);
        throw error;
    }
};

log said 'delete success' but it is actually not.

enter image description here


How can I delete file immediately from s3 after upload images.

1 Answers

This line:

console.log(fileName, " delete success");

is outputting the fileName, followed by "delete success".

However, your screenshot is showing that the fileName starts with https://:

Debug log

This is not a valid Key in Amazon S3!

I suggest that you add params.Key to your debug statement so that you can see what value is being sent to S3 in the delete_file() request. It probably doesn't match the actual name of the object in the S3 bucket.

Related