我用Django编写了一个带有FileField的电子邮件表单类。我想通过检查mimetype来检查上传的文件的类型。随后,我希望将文件类型限制为pdfs、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验证上传文件的文件类型的有效方法是什么?
发布于 2011-12-28 05:17:40
Stan用buffer描述了一个很好的变体。不幸的是,这种方法的弱点是从内存中读取文件。另一种选择是使用临时存储的文件:
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)在指定的临时文件仍处于打开状态时,是否可以使用该名称再次打开文件,这在不同的平台上是不同的(在Unix上可以这样使用;在Windows NT或更高版本上不能这样使用)。
因此,您可能希望像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()此外,您可能希望在read()之后执行seek(0)
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)发布于 2011-12-28 03:46:03
在你看来,为什么不尝试一下这样的东西呢:
m = magic.Magic()
m.from_buffer(request.FILES['my_file_field'].read())或者使用request.FILES代替form.cleaned_data,如果django.forms.Form确实不是一个选项的话。
发布于 2014-10-17 14:45:56
mime = magic.Magic(mime=True)
attachment = form.cleaned_data['attachment']
if hasattr(attachment, 'temporary_file_path'):
# file is temporary on the disk, so we can get full path of it.
mime_type = mime.from_file(attachment.temporary_file_path())
else:
# file is on the memory
mime_type = mime.from_buffer(attachment.read())此外,您可能希望在read()之后执行seek(0)
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)来自Django code的示例。在验证过程中对图像字段执行。
https://stackoverflow.com/questions/8647401
复制相似问题