将Base64映像上传到S3并返回URL [英] Upload Base64 Image to S3 and return URL

查看:27
本文介绍了将Base64映像上传到S3并返回URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python将base64映像上传到S3存储桶。 我用谷歌搜索了一下,找到了几个答案,但没有一个对我管用。有些答案用的是boto,而不是boto 3,因此对我来说毫无用处。 我也尝试过此链接:Boto3: upload file from base64 to 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存储桶并从中获取URL的正确方式是什么?

推荐答案

您没有提到如何获得base64。为了进行复制,我的代码片段使用requests库从Internet获取图像,然后使用base64库将其转换为base64。

这里的诀窍是确保您要上传的base64字符串不包含data:image/jpeg;base64前缀。 而且,正如@dmico在评论中提到的,您应该使用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的详细信息。

这篇关于将Base64映像上传到S3并返回URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆