使用boto,在s3上已存在的文件上设置content_type

时间:2021-07-16 21:07:42

I'm using django storages with the s3boto backend. As per this issue, http://code.larlet.fr/django-storages/issue/5/s3botostorage-set-content-type-header-acl-fixed-use-http-and-disable-query-auth-by I have a bunch of files (all of them) that have content type 'application/octet-stream'. Given that I have an instance of <class 'boto.s3.key.Key'>, how can I set the content_type?

我正在使用带有s3boto后端的django存储。根据这个问题,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'。鉴于我有 的实例,我该如何设置content_type? '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 个解决方案

#1


16  

There is no way to modify the content type (or any other metadata) associated with a file after it has been created. You can, however, copy the file on the server side and modify the metadata in the process. Here is a gist on github that should help:

在创建文件后,无法修改与文件关联的内容类型(或任何其他元数据)。但是,您可以在服务器端复制文件并修改该过程中的元数据。这是github上的一个要点,应该有所帮助:

https://gist.github.com/1791086

https://gist.github.com/1791086

Contents:

内容:

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

米奇

#1


16  

There is no way to modify the content type (or any other metadata) associated with a file after it has been created. You can, however, copy the file on the server side and modify the metadata in the process. Here is a gist on github that should help:

在创建文件后,无法修改与文件关联的内容类型(或任何其他元数据)。但是,您可以在服务器端复制文件并修改该过程中的元数据。这是github上的一个要点,应该有所帮助:

https://gist.github.com/1791086

https://gist.github.com/1791086

Contents:

内容:

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

米奇