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

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

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

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

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

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


当前回答

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

检查files是否为mp3

from mutagen.mp3 import MP3, HeaderNotFoundError  

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

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

其他回答

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

2017年更新

不需要去github,它在PyPi上以不同的名字:

pip3 install --user python-magic
# or:
sudo apt install python3-magic  # Ubuntu distro package

代码也可以简化:

>>> import magic

>>> magic.from_file('/tmp/img_3304.jpg', mime=True)
'image/jpeg'

比使用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匹配。

在python 2.6中:

import shlex
import subprocess
mime = subprocess.Popen("/usr/bin/file --mime " + shlex.quote(PATH), shell=True, \
    stdout=subprocess.PIPE).communicate()[0]

我首先尝试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