Django ImageField验证(是否足够)? [英] Django ImageField validation (is it sufficient)?

查看:93
本文介绍了Django ImageField验证(是否足够)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多用户上传的内容,并且我想确认上传的图像文件实际上不是恶意脚本。在Django文档中,它声明ImageField:

I have a lot of user uploaded content and I want to validate that uploaded image files are not, in fact, malicious scripts. In the Django documentation, it states that ImageField:

从FileField继承所有属性和方法,但还要验证上载的对象是有效的图像。

"Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image."

那是完全准确的吗?我了解到,压缩或以其他方式处理图像文件是一种很好的验证测试。我假设PIL会执行类似的操作。...

Is that totally accurate? I've read that compressing or otherwise manipulating an image file is a good validation test. I'm assuming that PIL does something like this....

ImageField可以在保护我的图像上传安全性方面大有帮助吗?

Will ImageField go a long way toward covering my image upload security?

推荐答案

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

Django validates the image uploaded via form using PIL. See 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()的以下内容:

PIL documentation states the following about 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仅在使用表单上传时才经过验证。如果您自己保存模型(例如使用某种下载脚本),则不会执行验证。

You should also note that ImageField is only validated when uploaded using form. If you save the model your self (e.g. using some kind of download script), the validation is not performed.

这篇关于Django ImageField验证(是否足够)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆