python - Django 使用 python-magic (libmagic) 来验证上传的文件

标签 python django python-magic libmagic

我正在尝试在 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/

相关文章:

windows - 运行 32 位 Python 2.7 构建的 64 位 Windows 10 的 python-magic 安装挑战

python - 当主脚本在子模块中时正确初始化 sys.path

python - Python 3.x 中的 final类——Guido 没有告诉我什么?

python - 尝试在终端上运行包含打开浏览器和搜索的代码的脚本

django - 使用 Nginx 作为代理服务器,使用 django 作为后端时如何正确处理重定向响应

django - 删除后模型对象是否可用?

python-2.7 - python-magic Windows错误: access violation writing 0x00000000

python - linux - watch 不通过 ssh 显示颜色

django - 在 Heroku 上的 python 应用程序中安装 gem 包

Python-magic 有 OSError : [WinError 193] error while running in 32-bit version of IDLE