Search code examples
pythonamazon-s3boto3tornado

Upload image to S3


I'm working on a web app using Python Tornado in which I have to upload images to S3. It's working. My process is the following:

  • Get file from request (sent using form-data)
  • Save it under temporary directory
  • Upload it to S3 bucket

But my question is,

Is there a way to avoid saving the file locally since I already have its content inside a variable? It's also for security purposes.


Solution

  • the question totally makes sense! You need to convert your in memory stored image to bytearray. Boto3 put_object supports bytes as described here: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object

    So just paste the variable that stores your image_bytearray to the Body in the put_object().

    import boto3 
    
    session = boto3.Session()
    s3 = session.client("s3")
    s3.put_object(Body = iamge_bytearray, Bucket='your-s3-bucket', Key='test/test.png')