Search code examples
djangoamazon-s3boto3dropzone.js

S3 image upload error with boto3 and dropzone.js


using this API i am able to upload the file to S3 using Postman.

i gave direct path to the file "/home/user/Downloads/black-rose.png"

header_logo = request.data['header_logo']

#local file path
data = open(header_logo, 'rb')

s3 = boto3.resource(
     's3',
     aws_access_key_id=ACCESS_KEY_ID,
     aws_secret_access_key=ACCESS_SECRET_KEY,
     config=Config(signature_version='s3v4')
 )
#generatre a random url
header_logo = "header_logo/" + get_random_string(length=20) + ".png"

#AWS foler & file name with public access
s3.Bucket(BUCKET_NAME).put_object(Key=header_logo, ContentType = 'image/png', Body=data, ACL='public-read')

when i give the direct file path its working, but my front end developer says he cant give direct file path using javascript so he is using a plugin "dropzonejs" to encrypt the file path which gives file like like this

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElEQVR4Xoy9B7hlZ3Xe/9u9nH5uL3OnabqkkTTqCFVAgA2SwQaX4GATHIc/DiFg

which on directly giving this data to the api throws error


Solution

  • You simply need to decode the base 64 representation of the image, and then upload the decoded result, note that the start of the string up to the firs comma is not actually part of the image, you need to trim the prefix.

    import base64
    
    image_string = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElEQVR4Xoy9B7hlZ3Xe/9u9nH5uL3OnabqkkTTqCFVAgA2SwQaX4GATHIc/DiFg"
    
    image_encoded = image_string[image_string.index(',') + 1:]
    
    image_data = base64.b64decode(image_encoded)
    

    Then you can upload to s3 the data of the image

    s3.Bucket(BUCKET_NAME).put_object(Key=header_logo, ContentType = 'image/png', Body=image_data, ACL='public-read')