使用boto设置已存在于S3上的文件的content_type
我正在使用django storages和s3boto这个后端。根据这个问题,http://code.larlet.fr/django-storages/issue/5/s3botostorage-set-content-type-header-acl-fixed-use-http-and-disable-query-auth-by,我有一堆文件(所有文件)它们的内容类型都是'application/octet-stream'。现在我有一个<class 'boto.s3.key.Key'>
的实例,我该如何设置内容类型呢?
In [29]: a.file.file.key.content_type
Out[29]: 'application/octet-stream'
In [30]: mimetypes.guess_type(a.file.file.key.name)[0]
Out[30]: 'image/jpeg'
In [31]: type(a.file.file.key)
Out[31]: <class 'boto.s3.key.Key'>
1 个回答
16
一旦文件创建后,就无法修改与之相关的内容类型(或者其他任何元数据)。不过,你可以在服务器上复制这个文件,并在复制的过程中修改元数据。这里有一个GitHub上的链接,可以帮助你理解:
https://gist.github.com/1791086
内容如下:
import boto
s3 = boto.connect_s3()
bucket = s3.lookup('mybucket')
key = bucket.lookup('mykey')
# Copy the key onto itself, preserving the ACL but changing the content-type
key.copy(key.bucket, key.name, preserve_acl=True,
metadata={'Content-Type': 'text/plain'})
key = bucket.lookup('mykey')
print key.content_type
Mitch