To establish custom metadata for S3 objects using the Axios PUT method, follow these steps:
Set up an Axios instance with the necessary headers and AWS credentials:
const axios = require('axios');
const AWS = require('aws-sdk');
const s3 = new AWS.S3({
accessKeyId: 'your_access_key_id',
secretAccessKey: 'your_secret_access_key'
});
const instance = axios.create({
baseURL: 'https://your-s3-bucket.s3.amazonaws.com',
headers: {
'x-amz-acl': 'public-read',
'Content-Type': 'image/jpeg'
}
});
Retrieve the object's current metadata using the S3 getObjectMetadata method:
const getObjectMetadata = async (key) => {
try {
const response = await s3.getObjectMetadata({
Bucket: 'your-s3-bucket',
Key: key
}).promise();
return response.Metadata;
} catch(error) {
console.log(error);
return {};
}
};
Define the metadata to be added or updated:
const metadata = {
'x-amz-meta-custom-key': 'custom-value'
};
Use the Axios PUT method to upload the object with the new metadata:
const putObject = async (key, data) => {
try {
const objectMetadata = await getObjectMetadata(key);
const response = await instance.put(key, data, {
headers: {
...metadata,
...objectMetadata
}
});
console.log(response.data);
} catch(error) {
console.log(error);
}
};
This will update the object's metadata with the custom key-value pair. Note that the object's ACL and content type headers also need to be included in the metadata for the PUT request.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-30 15:45:46 +0000
Seen: 14 times
Last updated: Jun 30 '23