Home > Back-end >  Get version ID of uploaded S3 file right after upload?
Get version ID of uploaded S3 file right after upload?

Time:02-16

I'm dealing with the inevitable issue of users being able to overwrite files in my bucket via a JavaScript S3 upload.

After uploading a file, assuming I have versioning enabled, is there a way to get the original version ID so I can store it in my database for retrieval later when displaying that file?

This is my current upload code:

s3.upload(params).on('httpUploadProgress', function(evt) {
                var uploaded = Math.round(evt.loaded / evt.total * 100);
                console.log(`File uploaded: ${uploaded}%`);
            }).send(function(err, data) {
                if(err){
                    alert(err);
                } else {
                    alert('File is uploaded successfully!');
                    console.log(data);
                }
            });

I do not see any version ID in the data response since it seems to be in the response headers. Is there a way to extract it from there?

CodePudding user response:

You're right; your code doesn't have access to the previous/original versionId.

I don't know your exact requirements, but I see two ways how to do this:

  1. Check the file metadata before upload with s3.headObject which return data.VersionId. If the file doesn't exist, it doesn't matter; otherwise, you can save the original version ID in DB.

  2. Don't save the versions in the DB at all, and fetch them with listObjectVersions when the file is displayed from S3.

CodePudding user response:

I was able to retrieve the original version ID immediately after upload using the following code (it uploads the image and then grabs the version right after using listObjectVersions):

s3.upload(params).on('httpUploadProgress', function(evt) {
                var uploaded = Math.round(evt.loaded / evt.total * 100);
                console.log(`File uploaded: ${uploaded}%`);
            }).send(function(err, data) {
                if(err){
                    alert(err);
                } else {
                    alert('File is uploaded successfully!');
                    console.log(data);
                    var params = {
                      Bucket: "mybucket", 
                      Prefix: "images/path-to-image.jpg"
                     };
                     s3.listObjectVersions(params, function(err, data) {
                       var versionId = data["Versions"][0]["VersionId"];
                       alert(versionId);
                   });
                }
            });

Be sure to have list object versions enabled in your bucket policy:

{
        "Sid": "Statement2",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:ListBucketVersions",
        "Resource": "arn:aws:s3:::mybucket"
    }
  • Related