如何使用boto3设置现有S3密钥的Content-Type?

leo*_*leo 7 python amazon-s3 boto3

我想使用boto3更新S3存储桶中现有对象的Content-Type,但是如何在不重新上传文件的情况下更新?

    file_object = s3.Object(bucket_name, key)
    print file_object.content_type
    # binary/octet-stream
    file_object.content_type = 'application/pdf'
    # AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)

我有没有在boto3错过的方法?

相关问题:

leo*_*leo 10

在boto3中似乎没有任何方法,但您可以复制该文件以覆盖自身.

要通过boto3使用AWS低级API执行此操作,请执行以下操作:

s3 = boto3.resource('s3')
api_client = s3.meta.client
response = api_client.copy_object(Bucket=bucket_name,
                                  Key=key,
                                  ContentType="application/pdf",
                                  MetadataDirective="REPLACE",
                                  CopySource=bucket_name + "/" + key)
Run Code Online (Sandbox Code Playgroud)

MetadataDirective="REPLACE"原来需要为S3覆盖文件,否则你将得到一个错误信息说This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes. .

或者你可以使用copy_from,正如Jordon Phillips在评论中指出的那样:

s3 = boto3.resource("s3")
object = s3.Object(bucket_name, key)
object.copy_from(CopySource={'Bucket': bucket_name,
                             'Key': key},
                 MetadataDirective="REPLACE",
                 ContentType="application/pdf")
Run Code Online (Sandbox Code Playgroud)

  • 副本也在资源中。[文档](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Object.copy_from) (2认同)