[英]Django with python-magic (libmagic) to verify uploaded files
我正在尝试在 django 中保存上传文件的 mime 类型。 我不需要拒绝某些类型的文件,我只需要跟踪上传文件的 mime 类型。 我这样做:
class Foo(models.Model):
document = models.FileField(upload_to="foo", null=False)
file_type = models.CharField(max_length=14)
def save(self, *args, **kwargs):
print(self.document.read()) #confirms that the file exists, and this prints a load of bytes, so it's a bytes object
filetype = magic.from_file(self.document.read())
self.file_type = filetype
return super().save(*args, **kwargs)
问题是filetype = magic.from_file(self.document.read())
抛出错误:“ValueError: Embedded null byte”。 该文件绝对没有损坏(在这种情况下,它是一个 png,所以我期待 image/png)。 from_file 似乎确实想要一个字节对象,而 self.document.read() 肯定会产生字节,所以我不确定问题是什么......
从文档:
>>> import magic
>>> magic.from_file("testdata/test.pdf")
'PDF document, version 1.2'
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'
>>> magic.from_file("testdata/test.pdf", mime=True)
'application/pdf'
from_file 采用文件名,或者您可以使用 from_buffer。 更多细节python-magic 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.