假设您想要在某个地方保存一堆文件,例如在blob中。假设您希望通过网页分发这些文件,并让客户端自动打开正确的应用程序/查看器。

假设:浏览器通过HTTP响应中的mime-type (content-type?)报头确定要使用哪个应用程序/查看器。

基于这个假设,除了文件的字节外,还需要保存MIME类型。

如何找到文件的MIME类型?我现在用的是Mac,但这应该也适用于Windows。

浏览器是否在将文件发布到网页时添加此信息?

是否有一个简洁的python库来查找这些信息?WebService还是(更好的)一个可下载的数据库?


当前回答

我首先尝试mimetypes库。如果它不起作用,我就使用python-magic库。

import mimetypes
def guess_type(filename, buffer=None):
mimetype, encoding = mimetypes.guess_type(filename)
if mimetype is None:
    try:
        import magic
        if buffer:
            mimetype = magic.from_buffer(buffer, mime=True)
        else:
            mimetype = magic.from_file(filename, mime=True)
    except ImportError:
        pass
return mimetype

其他回答

mimetypes模块只是基于文件扩展名来识别文件类型。如果尝试恢复没有扩展名的文件的文件类型,mimetypes将不起作用。

你没有说明你使用的是什么web服务器,但Apache有一个很好的小模块,叫做Mime Magic,它用来确定文件的类型,当被告知这样做。它读取文件的一些内容,并试图根据找到的字符找出文件的类型。正如Dave Webb提到的,python下的MimeTypes模块可以工作,只要有一个方便的扩展。

或者,如果您坐在UNIX机器上,您可以使用sys。popen('file -i ' + fileName, mode='r')获取MIME类型。Windows应该有一个等效的命令,但我不确定它是什么。

Python 3参考:https://docs.python.org/3.2/library/mimetypes.html

mimetypes.guess_type(url, strict=True) Guess the type of a file based on its filename or URL, given by url. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header. encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively. The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized.

import mimetypes
print(mimetypes.guess_type("sample.html"))

有3个不同的库包装libmagic。

其中2个在pypi上可用(所以PIP安装可以工作):

filemagic python-magic

另一种类似于python-magic的方法可以在最新的libmagic源代码中直接获得,它可能是您的linux发行版中所拥有的。

在Debian中,python-magic包就是这样的,它像toivotuo说的那样被使用,它并没有像Simon Zimmermann说的那样被淘汰(IMHO)。

在我看来,这是另一种说法(出自《libmagic》的原作者)。

太糟糕了,pypi上不能直接使用。

我首先尝试mimetypes库。如果它不起作用,我就使用python-magic库。

import mimetypes
def guess_type(filename, buffer=None):
mimetype, encoding = mimetypes.guess_type(filename)
if mimetype is None:
    try:
        import magic
        if buffer:
            mimetype = magic.from_buffer(buffer, mime=True)
        else:
            mimetype = magic.from_file(filename, mime=True)
    except ImportError:
        pass
return mimetype