2012-02-10 31 views
7

我使用django存儲與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'>的實例,我如何設置content_type?使用boto,在s3上已經存在的文件上設置content_type

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'> 

回答

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 

米奇

相關問題