使用Boto3将base64字符串(图像数据)上传到Python中的S3服务器,并获取URL作为回报

发布于 2021-01-29 14:10:56

我正在尝试使用Python将基本64字符串(基本上是图像数据)上传到S3存储桶。我已经用谷歌搜索并得到了一些答案,但是没有一个对我有用。而且有些答案使用的是boto而不是boto3,因此它们对我毫无用处。我也尝试了此链接:Boto3:将文件从base64上传到S3,Object由于s3未知,所以它对我不起作用。

以下是我到目前为止的代码:

import boto3

s3 = boto3.client('s3')
filename = photo.personId + '.png'
bucket_name = 'photos-collection'
dataToPutInS3 = base64.b64decode(photo.url[23:])

将此变量dataToPutInS3数据上传到s3存储桶并从中获取网址的正确方法是什么。

关注者
0
被浏览
116
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您没有提到如何获得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的更多信息。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看