假设您想要在某个地方保存一堆文件,例如在blob中。假设您希望通过网页分发这些文件,并让客户端自动打开正确的应用程序/查看器。
假设:浏览器通过HTTP响应中的mime-type (content-type?)报头确定要使用哪个应用程序/查看器。
基于这个假设,除了文件的字节外,还需要保存MIME类型。
如何找到文件的MIME类型?我现在用的是Mac,但这应该也适用于Windows。
浏览器是否在将文件发布到网页时添加此信息?
是否有一个简洁的python库来查找这些信息?WebService还是(更好的)一个可下载的数据库?
在Python 3中。X和webapp的url文件不能有扩展名或假扩展名。您应该安装python-magic,使用
pip3 install python-magic
对于Mac OS X,你也应该使用libmagic
brew install libmagic
代码片段
import urllib
import magic
from urllib.request import urlopen
url = "http://...url to the file ..."
request = urllib.request.Request(url)
response = urlopen(request)
mime_type = magic.from_buffer(response.readline())
print(mime_type)
或者,您可以在read中输入一个大小
import urllib
import magic
from urllib.request import urlopen
url = "http://...url to the file ..."
request = urllib.request.Request(url)
response = urlopen(request)
mime_type = magic.from_buffer(response.read(128))
print(mime_type)