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

Adi*_*Adi 43 python amazon-s3 boto boto3

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

s3 = session.resource('s3')
bucket = s3.Bucket(S3_BUCKET)
bucket.upload_file(file, key)
Run Code Online (Sandbox Code Playgroud)

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

小智 69

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

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

  • 无论如何不适用于 boto3:`botocore.exceptions.ParamValidationError:参数验证失败:输入中的未知参数:“ExtraArgs”,必须是以下之一:ACL、Body、Bucket、CacheControl、ContentDisposition、ContentEncoding、ContentLanguage、ContentLength, ContentMD5、ContentType、Expires、GrantFullControl、GrantRead、GrantReadACP、GrantWriteACP、密钥、元数据、ServerSideEncryption、StorageClass、WebsiteRedirectLocation、SSECustomerAlgorithm、SSECustomerKey、SSECustomerKeyMD5、SSEKMSKeyId、RequestPayer、标记、ObjectLockMode、ObjectoldLockRetainUntilH (2认同)
  • 与 boto3 一起为我工作 (2认同)

Adi*_*Adi 32

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

s3 = boto3.resource('s3')
object_acl = s3.ObjectAcl('bucket_name','object_key')
response = object_acl.put(ACL='public-read')
Run Code Online (Sandbox Code Playgroud)

有关详细信息:http://boto3.readthedocs.io/en/latest/reference/services/s3.html#objectacl

  • 如果你只更新一个对象`boto3.resource('s3'),那么就是一个班轮.ObjectAcl('bucket_name','object_key').put(ACL ='public-read')` (5认同)

Roh*_*chi 5

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

"s3:GetObjectAcl",
"s3:PutObjectAcl"
Run Code Online (Sandbox Code Playgroud)

  • 在哪里声明 Action 数组? (6认同)