如何使用boto3设置现有S3密钥的Content-Type? [英] How do I set the Content-Type of an existing S3 key with boto3?

查看:329
本文介绍了如何使用boto3设置现有S3密钥的Content-Type?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用boto3更新S3存储桶中现有对象的Content-Type,但是如何做到这一点,而不必重新上传文件?

I want to update the Content-Type of an existing object in a S3 bucket, using boto3, but how do I do that, without having to re-upload the file?

    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

在boto3中是否有一种我错过的方法?

Is there a method for this I have missed in boto3?

相关问题:

  • How to set Content-Type on upload
  • How to set the content type of an S3 object via the SDK?

推荐答案

在boto3中似乎没有用于此目的的任何方法,但是您可以复制文件以覆盖自身.

There doesn't seem to exist any method for this in boto3, but you can copy the file to overwrite itself.

要通过boto3使用AWS低级API进行此操作,请按以下步骤操作:

To do this using the AWS low level API through boto3, do like this:

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)

事实证明,S3覆盖文件需要使用MetadataDirective="REPLACE",否则您将收到一条错误消息,提示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. .

The MetadataDirective="REPLACE" turns out to be required for S3 to overwrite the file, otherwise you will get an error message saying 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)在评论中指出的那样:

Or you can use copy_from, as pointed out by Jordon Phillips in the comments:

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

这篇关于如何使用boto3设置现有S3密钥的Content-Type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆