Python 如何将文件上传到 S3 并使用 boto3 将其公开?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41904806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:49:01  来源:igfitidea点击:

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

pythonamazon-s3botoboto3

提问by Adi

I am able to upload an image file using:

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

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

However, I want to make the file public too. I tried looking up for some functions to set ACL for the file but seems like boto3 have changes their API and removed some functions. Is there a way to do it in the latest release of boto3?

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

采纳答案by Adi

I was able to do it using objectAcl API:

我能够使用 objectAcl API 做到这一点:

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

For details: http://boto3.readthedocs.io/en/latest/reference/services/s3.html#objectacl

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

回答by Bill Baker

To upload and set permission to publicly-readable in one step, you can use:

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

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

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

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

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

回答by Rohan Bagchi

Adi's wayworks. However, if you were like me, you might have run into an access denied issue. This is normally caused by broken permissions of the user. I fixed it by adding the following to the Actionarray:

阿迪的方法奏效了。但是,如果您像我一样,可能会遇到拒绝访问的问题。这通常是由用户权限损坏引起的。我通过将以下内容添加到Action数组中来修复它:

"s3:GetObjectAcl",
"s3:PutObjectAcl"