我正在尝试在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()肯定会产生字节,所以我不确定问题是什么……
发布于 2019-04-24 06:03:22
从文档中:
>>> 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。
https://stackoverflow.com/questions/55819828
复制相似问题