gpt4 book ai didi

Django ImageField 验证(是否足够)?

转载 作者:行者123 更新时间:2023-12-04 14:18:40 25 4
gpt4 key购买 nike

我有很多用户上传的内容,我想验证上传的图像文件实际上不是恶意脚本。在 Django 文档中,它指出 ImageField:

“从 FileField 继承所有属性和方法,但也验证上传的对象是有效的图像。”

这完全准确吗?我读过压缩或以其他方式操作图像文件是一个很好的验证测试。我假设 PIL 会做这样的事情......

ImageField 会在很大程度上覆盖我的图像上传安全吗?

最佳答案

Django 使用 PIL 验证通过表单上传的图像。
https://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L519

try:
# load() is the only method that can spot a truncated JPEG,
# but it cannot be called sanely after verify()
trial_image = Image.open(file)
trial_image.load()

# Since we're about to use the file again we have to reset the
# file object if possible.
if hasattr(file, 'reset'):
file.reset()

# verify() is the only method that can spot a corrupt PNG,
# but it must be called immediately after the constructor
trial_image = Image.open(file)
trial_image.verify()
...
except Exception: # Python Imaging Library doesn't recognize it as an image
raise ValidationError(self.error_messages['invalid_image'])

PIL 文档说明了有关 verify() 的以下内容:

Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file.



您还应该注意 ImageField 仅在使用表单上传时进行验证。如果您自己保存模型(例如使用某种下载脚本),则不会执行验证。

关于Django ImageField 验证(是否足够)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5770660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com