Django ImageField 验证(是否足够)?

标签 django security file-upload django-models

我有很多用户上传的内容,我想验证上传的图像文件实际上不是恶意脚本。在 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/

相关文章:

python - Django 中的全局小数舍入选项

python - 将一个休息资源路由为第二个休息资源的子资源

php - 如何使用jquery序列化进行文件上传

php - jQuery 文件上传和获取 $_Files

Django : Unable to import model from another App

Django- 多个端口上的 session cookie 和站点

algorithm - 如何将 DigestMethod 设置为 Sha 256 WCF?

Android 私有(private)内容提供商?

ios - 字符串数组的安全数据持久性

PHP:如何缩短网址+从数据库中获取数据