Вы не упомянули, как вы получили base64. Для воспроизведения мой фрагмент кода получает изображение из Интернета с использованием библиотеки requests
, а затем преобразует его в base64 с использованием библиотеки base64
.
Хитрость заключается в том, чтобы убедиться, что строка base64, которую вы хотите загрузить, не содержит префикс data:image/jpeg;base64
. И, как упоминалось в комментариях @dmigo, вы должны работать с boto3.resource , а не с 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)
Подробнее о S3.Object.put .