我在 Django 中编写了一个带有 FileField 的电子邮件表单类。我想通过检查其 mimetype 来检查上传文件的类型。随后,我想将文件类型限制为 pdf、word 和打开的 Office 文档。
为此,我已经安装了 python-magic,并希望按照 python-magic 的规范检查文件类型:
mime = magic.Magic(mime=True)
file_mime_type = mime.from_file('address/of/file.txt')
但是,最近上传的文件在我的服务器上缺少地址。我也不知道 mime 对象有任何类似于“from_file_content”的方法来检查给定文件内容的 mime 类型。
在 Django 表单中使用 magic 来验证上传文件的文件类型的有效方法是什么?
最佳答案
斯坦描述了带有缓冲液的良好变体。不幸的是,这种方法的弱点是将文件读取到内存中。另一种选择是使用临时存储文件:
import tempfile
import magic
with tempfile.NamedTemporaryFile() as tmp:
for chunk in form.cleaned_data['file'].chunks():
tmp.write(chunk)
print(magic.from_file(tmp.name, mime=True))
此外,您可能想检查文件大小:
if form.cleaned_data['file'].size < ...:
print(magic.from_buffer(form.cleaned_data['file'].read()))
else:
# store to disk (the code above)
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
所以你可能想像 so 那样处理它:
import os
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
for chunk in form.cleaned_data['file'].chunks():
tmp.write(chunk)
print(magic.from_file(tmp.name, mime=True))
finally:
os.unlink(tmp.name)
tmp.close()
此外,您可能想要seek(0)
在read()
之后:
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
关于django - 如何使用 magic 来验证 Django 表单 clean 方法中的文件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647401/