Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To establish custom metadata for S3 objects using the Axios PUT method, follow these steps:

  1. 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'
    }
    });
    
  2. 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 {};
    }
    };
    
  3. Define the metadata to be added or updated:

    const metadata = {
    'x-amz-meta-custom-key': 'custom-value'
    };
    
  4. 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.