我正在尝试在 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:嵌入空字节”。该文件绝对没有损坏(在本例中,它是一个 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 .
关于python - Django 使用 python-magic (libmagic) 来验证上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819828/