首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python-magic (libmagic)验证上传的文件的Django

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

Stack Overflow用户
提问于 2019-04-24 05:42:51
回答 1查看 775关注 0票数 1

我正在尝试在django中保存上传文件的mime类型。我不需要拒绝某些类型的文件,我只需要跟踪上传文件的mime类型。我正在做这个:

代码语言:javascript
复制
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()肯定会产生字节,所以我不确定问题是什么……

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-24 06:03:22

从文档中:

代码语言:javascript
复制
>>> 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55819828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档