Home > Enterprise >  How to Change System Metadata in AWS S3
How to Change System Metadata in AWS S3

Time:05-03

I am trying to change the metadata of an image in an s3 bucket through lambda, this lambda triggers when an object is uploaded. But for some reason when I update the metadata through copy_from it adds user metadata instead of the System Metadata like this: enter image description here

Is there a special way to edit the system metadata? My code is:

import json
import boto3
import urllib
s3 = boto3.resource('s3')
def lambda_handler(event, context):
    # TODO implement
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])
    s3_object = s3.Object(bucket, key)
    s3_object.metadata.update({'Content-Type':'image/png'})
    s3_object.copy_from(CopySource={'Bucket':bucket, 'Key':key}, Metadata=s3_object.metadata, MetadataDirective='REPLACE')
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

CodePudding user response:

Content-Type is special metadata categorised as system defined metadata, and there are other means to update it. It is derived based on the contents of the object when it is created/uploaded.

Let's say you want to update System defined Content-Type metadata. Try with this code, which updates System defined metadata and also adds a user defined metadata:

    s3_object.metadata.update({'My-Metadata':'abc'})
    s3_object.copy_from(CopySource={'Bucket':BUCKET_NAME, 'Key':OBJECT_KEY}, ContentType='image/png', Metadata=s3_object.metadata, MetadataDirective='REPLACE')

As you see here, copy_from takes parameter ContentType explicitly to update content-type. One does not need to use metadata json to update this parameter. Use metadata json to update other user defined parameters.

  • Related