如何使用 boto3 将文件上传到 S3 并使其 public?

How to upload a file to S3 and make it public using boto3?

我可以使用以下方式上传图像文件:

s3 = session.resource('s3')
bucket = s3.Bucket(S3_BUCKET)
bucket.upload_file(file, key)

不过,我也想制作文件public。我尝试查找一些函数来为文件设置 ACL,但似乎 boto3 更改了它们的 API 并删除了一些函数。有没有办法在最新版本的 boto3 中做到这一点?

我可以使用 objectAcl API:

s3 = boto3.resource('s3')
object_acl = s3.ObjectAcl('bucket_name','object_key')
response = object_acl.put(ACL='public-read')

详情:http://boto3.readthedocs.io/en/latest/reference/services/s3.html#objectacl

有效。但是,如果您像我一样,可能 运行 遇到访问被拒绝的问题。这通常是由于用户权限被破坏引起的。 我通过将以下内容添加到 Action 数组来修复它:

"s3:GetObjectAcl",
"s3:PutObjectAcl"

要一步上传并设置权限为公开可读,您可以使用:

bucket.upload_file(file, key, ExtraArgs={'ACL':'public-read'})

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html#the-extraargs-parameter

在最新版本的 boto 中,ACL 可用作常规参数 - 似乎在使用 S3 客户端和资源时都是如此。您可以只指定 ACL="public_read" 而不必用 ExtraParams 或使用 ObjectAcl API.

包装它

如上所述设置ACL="public-read"

此外,请确保您的存储桶策略 Resource 行 具有裸 arn 和 /* arn 格式。 两者都没有会导致奇怪的权限问题。

...
"Resource": ["arn:aws:s3:::my_bucket/*", "arn:aws:s3:::my_bucket"]