I´m receiving a image through an API (binary type) in a lambda function. So to upload the image to the S3 I have read that I have to decode the image so this is the code:
def lambda_handler(event, context):
# Decodifica la cadena base64
img_data = base64.b64decode(event['body'])
# Guarda la imagen en un archivo temporal
aux_path = '/tmp/{}.jpg'.format(generate_unique_id())
with open(aux_path, 'wb') as f:
f.write(img_data)
# Sube la imagen a S3
bucket = 'myawsbuckedtesting'
s3_key = '{}.jpg'.format(generate_unique_id())
s3.upload_file(aux_path, bucket, s3_key)
return {
'statusCode': 200,
'body': json.dumps({'message': 'file saved successfully'}),
'headers': {'Access-Control-Allow-Origin': '*'}
}
But I’m getting an error in the first line of code of my lambda function where I’m trying to decode the image.
[ERROR] ValueError: string argument should contain only ASCII characters
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 16, in lambda_handler
img_data = base64.b64decode(event['body'])
File "/var/lang/lib/python3.12/base64.py", line 83, in b64decode
s = _bytes_from_decode_data(s)
File "/var/lang/lib/python3.12/base64.py", line 39, in _bytes_from_decode_data
raise ValueError('string argument should contain only ASCII characters')
How can I fix my code?
I expect to receive the image and save in the s3 in AWS. I have tried to modify the binary types accepted in the API with “/” but this does not solve the error.
Tom Smiths is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.