您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

python 2022/1/1 18:27:12 有502人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶