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

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

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

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

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

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


当前回答

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"))

其他回答

这似乎很简单

>>> from mimetypes import MimeTypes
>>> import urllib 
>>> mime = MimeTypes()
>>> url = urllib.pathname2url('Upload.xml')
>>> mime_type = mime.guess_type(url)
>>> print mime_type
('application/xml', None)

请参阅旧帖

更新-在python 3+版本中,现在更方便了:

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

比使用mimetypes库更可靠的方法是使用python-magic包。

import magic
m = magic.open(magic.MAGIC_MIME)
m.load()
m.file("/tmp/document.pdf")

这相当于使用file(1)。

在Django中,还可以确保MIME类型与UploadedFile.content_type匹配。

13年后…… 本页上关于python3的大多数答案不是过时就是不完整。 要获得我使用的文件的mime类型:

import mimetypes

mt = mimetypes.guess_type("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
if mt:
    print("Mime Type:", mt[0])
else:
    print("Cannot determine Mime Type")

# Mime Type: application/pdf

现场演示


来自Python文档:

mimetype。guess_type (url,严格= True)

根据文件的文件名、路径或URL (URL)来猜测文件的类型。URL可以是字符串或类似路径的对象。

返回值是一个元组(type, encoding),如果无法猜到类型(缺少或未知后缀),则type为None,或者是一个'type/subtype'形式的字符串,可用于MIME内容类型头。

encoding为None,表示没有编码或用于编码的程序名称(例如compress或gzip)。该编码适合作为Content-Encoding标头使用,而不是Content-Transfer-Encoding标头。映射是表驱动的。编码后缀区分大小写;类型后缀首先区分大小写,然后不区分大小写。

可选的strict参数是一个标志,指定已知MIME类型列表是否仅限于在IANA注册的正式类型。当strict为True(默认值)时,只支持IANA类型;当strict为False时,一些额外的非标准但常用的MIME类型也会被识别出来。

在3.8版更改:增加了对url是类路径对象的支持。

我很惊讶没有人提到它,但是pyments能够对mime类型做出有根据的猜测,特别是文本文档。

pyuments实际上是一个Python语法高亮显示库,但它有一个方法,可以根据您的文档是500种受支持的文档类型中的哪一种进行有根据的猜测。 即c++ vs c# vs Python vs等等

import inspect

def _test(text: str):
    from pygments.lexers import guess_lexer
    lexer = guess_lexer(text)
    mimetype = lexer.mimetypes[0] if lexer.mimetypes else None
    print(mimetype)

if __name__ == "__main__":
    # Set the text to the actual defintion of _test(...) above
    text = inspect.getsource(_test)
    print('Text:')
    print(text)
    print()
    print('Result:')
    _test(text)

输出:

Text:
def _test(text: str):
    from pygments.lexers import guess_lexer
    lexer = guess_lexer(text)
    mimetype = lexer.mimetypes[0] if lexer.mimetypes else None
    print(mimetype)


Result:
text/x-python

现在,它不是完美的,但如果您需要能够分辨出500种文档格式中正在使用的是哪一种,这是非常有用的。

我已经尝试了很多例子,但与Django mutagen发挥得很好。

检查files是否为mp3

from mutagen.mp3 import MP3, HeaderNotFoundError  

try:
    audio = MP3(file)
except HeaderNotFoundError:
    raise ValidationError('This file should be mp3')

缺点是你检查文件类型的能力是有限的,但如果你不仅想检查文件类型,而且还想访问其他信息,这是一个很好的方法。