J. Doe
J. Doe

Reputation: 671

Sending image from AWS Lambda function gets corrupted

I have an image in an s3 bucket that I'm trying to pass along in a response. I managed to do so but the file gets corrupted on the way.

Lambda code:

def get_file(file):
    s3 = boto3.client('s3')
    bucket = 'my_bucket'
    file = s3.get_object(Bucket=bucket, Key=file)['Body'].read()
    encoded_bytes = base64.b64encode(file)
    headers = {
        'Content-Type': 'image/jpeg'
    }
    response = {
        'statusCode': 200,
        'IsBase64Encoded': True,
        'body': json.dumps({'file': base64.b85encode(encoded_bytes).decode('utf-8')}),
        'headers': headers
    }
    return response

Converting it to bytes again and attempt to save it as an image:

img = str.encode(string)
with open('image.jpeg','wb') as f:
    f.write(img)

Am I doing something wrong when sending it from AWS?

Thanks!

Upvotes: 0

Views: 308

Answers (1)

ZEE
ZEE

Reputation: 5849

Instead of downloading the image in Lambda and sending it in the response, you better use s3 signed URL, it allows you to generate a temporarily signed URL, then you can send this URL to the client and let it download the image directly from s3.

Upvotes: 1

Related Questions