'Get version ID of uploaded S3 file right after upload?
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?
Solution 1:[1]
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:
Check the file metadata before
uploadwith s3.headObject which returndata.VersionId. If the file doesn't exist, it doesn't matter; otherwise, you can save the original version ID in DB.Don't save the versions in the DB at all, and fetch them with listObjectVersions when the file is displayed from S3.
Solution 2:[2]
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"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zdenek F |
| Solution 2 | Anthony Frizalone |
