使用Boto3将base64字符串(图像数据)上传到Python中的S3服务器,并获取URL作为回报 [英] Upload a base64 string(Image Data) to S3 server in Python using Boto3 and get URL in return
问题描述
我正在尝试将基本的64位字符串上载到使用Python的S3存储桶中.
我已经用谷歌搜索并得到了一些答案,但是没有一个对我有用.而且有些答案使用的是boto而不是boto3,因此对我来说毫无用处.
我也尝试过此链接: Boto3:将文件从base64上传到S3 ,但它对我不起作用,因为s3不知道Object
方法.
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 some answers use boto and not boto3, hence they are useless to me.
I have also tried this link: Boto3: upload file from base64 to S3 but it is not working for me as Object
method is unknown to the s3.
以下是我的代码:
import boto3
s3 = boto3.client('s3')
filename = photo.personId + '.png'
bucket_name = 'photos-collection'
dataToPutInS3 = base64.b64decode(photo.url[23:])
将变量dataToPutInS3
数据上传到s3存储桶并从中获取网址的正确方法是什么.
What is the correct way to upload this variable dataToPutInS3
data to s3 bucket and get a url back from it.
推荐答案
您没有提到如何获得base64.为了重现,我的代码段使用 requests
库从互联网获取图像,并稍后使用 base64
库将其转换为base64.
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.
此处的技巧是确保要上传的base64字符串不包含data:image/jpeg;base64
前缀.
而且,正如评论中提到的@dmigo一样,您应该使用 boto3.resource 而不是boto3.client.
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)
有关 S3的更多信息.Object.put .
这篇关于使用Boto3将base64字符串(图像数据)上传到Python中的S3服务器,并获取URL作为回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!