How To: Set and Retrieve Metadata of an S3 Object
Join the DZone community and get the full member experience.
Join For FreeIn the article we will see how to upload the metadata of an object while uploading to S3 programatically.
I will be using Node.js to demonstrate the same.
Before jumping to that let’s see what is metadata and it’s use case
We have 2 types of metadata
- System Metadata E.g. Date, Content-Length
- User defined metadata
While we upload the object, we can add custom metadata about the object along that as a key-value pair
Note: All user-defined metadata keys in lowercase
Let’s say we are having a platform where contents are added by multiple organization. In this scenario adding OrganizationID as one of the metadata will be handy.
Following code helps you to upload an object to s3 along it’s metadata.
var AWS = require('aws-sdk')
var credentials = require('./cred');
var s3 = new AWS.S3({accessKeyId: credentials.accesskey,
secretAccessKey: credentials.secretkey,region:credentials.region});
var fs = require('fs');
fs.readFile('file2.txt', function (err, data) {
if (err) { throw err; }
var base64data = new Buffer(data, 'binary');
s3.putObject({
Bucket: 'uploadmetatest',
Key: 'vijaykishan.txt',
Metadata: {OrgID: 'TEKKIHUT', PROFILE: 'HD'},
Body: base64data,
ACL: 'public-read'
}, function (resp) {
console.log('Successfully uploaded package.');
});
});
Let’s see how to retrieve the metadata of an uploaded object using node.js.
Following code helps you to retrieve the metadata of an object uploaded to s3.
xxxxxxxxxx
var params = {
Bucket: "uploadmetatest",
Key: "file2.txt"
};
s3.headObject(params, function (err, data) { if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data.Metadata['orgid']);
console.log(data.Metadata['profile']);
}
});
Note
The PUT request header is limited to 8 KB in size. Within the PUT request header, the user-defined metadata is limited to 2 KB in size. The size of user-defined metadata is measured by taking the sum of the number of bytes in the UTF-8 encoding of each key and value.
Hope this helps
Opinions expressed by DZone contributors are their own.
Comments