I'm trying to write a lambda function to upload files to my S3 bucket.
I'm new to coding so I don't understand why this doesn't work.
I get a "KeyError" for Body. Can anyone explain what this means and how do I fix my code?
Thanks in advance.
import base64
import boto3
import json
import uuid
s3 = boto3.client('s3')
def lambda_handler(event, context):
print(event)
response = s3.put_object(
Bucket='s3-bucket',
Key=str(uuid.uuid4()) + '.jpg',
Body=event.body,
)
image = response['Body'].read()
return {
'headers': {
"Content-Type": "image/jpg",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Credentials": True,
},
'statusCode': 200,
'body': base64.b64encode(image).decode('utf-8'),
'isBase64Encoded': True
}
I tried replacing Body = event.body with Body=event['body'] or Body = event('body') but it still doesn't work.
I expect my lambda function to be able to upload a file to my S3 bucket.