使用 Boto3 通过 Python 将图像上传到 Amazon S3 的最有效方法

问题描述 投票:0回答:2

我正在实现 Boto3 将文件上传到 S3,一切正常。我正在做的过程如下:

我从 FileReader Javascript 对象获取 base64 图像。然后我通过ajax将base64发送到服务器,解码base64图像并生成一个随机名称来重命名

key
参数

data = json.loads(message['text'])
dec = base64.b64decode(data['image'])
s3 = boto3.resource('s3')
s3.Bucket('bucket_name').put_object(Key='random_generated_name.png', Body=dec,ContentType='image/png',ACL='public-read')

这工作正常,但就性能而言,有更好的方法来改进它吗?

python boto3
2个回答
3
投票

我用过这个,我相信它更有效并且更Pythonic。

    import boto3
    s3 = boto3.client('s3')
    bucket = 'your-bucket-name'
    file_name = 'location-of-your-file'
    key_name = 'name-of-file-in-s3'
    s3.upload_file(file_name, bucket, key_name)

2
投票

要将内存中图像直接上传到 AWS S3 存储桶,如 @Yterle 所说,您应该使用

upload_fileobj
(可以从较低级别的
boto3.client
接口而不是其较高级别的包装器进行访问) ,
boto3.resource
。)

import io
import json
import base64
import boto3

s3_resource = boto3.resource('s3')
s3_client = boto3.client('s3')

BUCKET = "bucket_name"
IMAGE_KEY = "random_generated_name.png"
MESSAGE = {"text": {"image": IMAGE_B64_BINARY_DATA}}

data = json.loads(MESSAGE["text"])
dec = base64.b64decode(data["image"])
# Transform the binary data into something
# which can be used like a file handle
image_filelike = io.BytesIO(dec)

# Upload in-memory object to S3 bucket
s3_client.upload_fileobj(
    Fileobj=image_filelike,
    Bucket=BUCKET,
    Key=IMAGE_KEY,
    ExtraArgs={"ContentType":"image/png", "ACL":"public-read"},
    Callback=None,
    Config=None)

# Optional: wait until the s3 object exists before exiting
s3_resource.Object(BUCKET, IMAGE_KEY).wait_until_exists()
© www.soinside.com 2019 - 2024. All rights reserved.