您没有提到如何获得base64。为了重现,我的代码片段使用了requests
库从互联网上获取图像,然后使用库将其转换为base64base64
。
这里的技巧是确保要上传的base64字符串不包含data:image/jpeg;base64
前缀。而且,正如评论中提到的@dmigo一样,您应该使用 而不是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的更多信息。