图像文件的 Django 内容类型

问题描述 投票:0回答:2

我想在上传之前检查文件类型:

content = self.cleaned_data['picture']
content_type = content.content_type.split('/')[0]

当我上传图片时出现错误:

'NoneType' object has no attribute 'content_type'

这里可能出了什么问题?

python django image identification imghdr
2个回答
7
投票
如果图像有效,

imghdr.what
将返回图像格式为字符串(gif、png等),否则返回
None

用途:

import imghdr
imghdr.what(value)

在上面的示例中

value
可以是文件(类)对象或文件名。


0
投票

注意:这不是答案。由于声誉限制,我无法发表评论。


imghdr
“自版本 3.11 起已弃用”,它将在 python3.13 中删除。 根据 PEP 594(第 3 方),替代方案是 filetypepuremagicpython-magic

截至 2024 年 3 月,文件类型最新版本和 python-magic 最新版本均于 2022 年发布。 似乎只有 puremagic 正在积极地 得到维护,但是

它不会尝试将文件与非魔法字符串进行匹配。换句话说,它不会像其他人那样在某个字节窗口内搜索字符串。

© www.soinside.com 2019 - 2024. All rights reserved.