Upload a base64 string(Image Data) to S3 server in Python using Boto3 and get URL in return

后端 未结 1 1097
我在风中等你
我在风中等你 2020-12-19 08:47

I am trying to upload a base 64 string , which is basically image data to an S3 bucket using Python. I have googled and got a few answers but none of them works for me. And

相关标签:
1条回答
  • 2020-12-19 09:35

    You didn't mention how do you get the base64. In order to reproduce,my code snippet getting the image from the internet using the requests library and later convert it to base64 using the base64 library.

    The trick here is to make sure the base64 string you want to upload doesn't include the data:image/jpeg;base64 prefix. And, as @dmigo mentioned in the comments, you should work with boto3.resource and not boto3.client.

        from botocore.vendored import requests
        import base64
        import boto3
    
        s3 = boto3.resource('s3')
        bucket_name = 'BukcetName'
        #where the file will be uploaded, if you want to upload the file to folder use 'Folder Name/FileName.jpeg'
        file_name_with_extention = 'FileName.jpeg'
        url_to_download = 'URL'
    
        #make sure there is no data:image/jpeg;base64 in the string that returns
        def get_as_base64(url):
            return base64.b64encode(requests.get(url).content)
    
        def lambda_handler(event, context):
            image_base64 = get_as_base64(url_to_download)
            obj = s3.Object(bucket_name,file_name_with_extention)
            obj.put(Body=base64.b64decode(image_base64))
            #get bucket location
            location = boto3.client('s3').get_bucket_location(Bucket=bucket_name)['LocationConstraint']
            #get object url
            object_url = "https://%s.s3-%s.amazonaws.com/%s" % (bucket_name,location, file_name_with_extention)
            print(object_url)
    

    More about S3.Object.put.

    0 讨论(0)
提交回复
热议问题