Using boto, set content_type on files which are already present on s3

↘锁芯ラ 提交于 2019-12-13 11:43:19

问题


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?

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:


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:

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



来源:https://stackoverflow.com/questions/9231029/using-boto-set-content-type-on-files-which-are-already-present-on-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!