2

I want to download an image from a bucket S3 and store in a variable, not in my local pc, how can I do it?

I'm using this code to store in local:

BUCKET_NAME = 'mybucket' 
KEYFILE = 'myImage.jpg' 

try:
    s3.Bucket(BUCKET_NAME).download_file(KEYFILE, 'myImageInLocal.jpg')          
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise
  • [python - Read file content from S3 bucket with boto3 - Stack Overflow](https://stackoverflow.com/questions/36205481/read-file-content-from-s3-bucket-with-boto3) – John Rotenstein Jun 30 '21 at 10:49

2 Answers2

5

You can download to BytesIO variable with download_fileobj:

from io import BytesIO

BUCKET_NAME = 'mybucket' 
KEYFILE = 'myImage.jpg' 

s3_file = BytesIO()

try:
    s3.Bucket(BUCKET_NAME).download_fileobj('myImageInLocal.jpg', s3_file)          
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

May be you can try with BytesIO()

import io
image_data = io.BytesIO()

in your try block

s3.Bucket(BUCKET_NAME).download_file(KEYFILE, image_data)  

so image_data is the variable that should have the image in byte format.