【发布时间】:2014-04-27 10:22:12
【问题描述】:
我想在 imagefield 上上传具有有限扩展名的文件。那么,如何验证我的图像字段仅适用于 jpg、bmp 和 gif。 另外,image字段默认采用哪个扩展名?
【问题讨论】:
-
验证几乎完全相同(只需使用检查扩展名的部分)。 AFAIK,接受哪些扩展没有默认限制。这取决于您来实施(使用链接的重复问题)
标签: django django-models
我想在 imagefield 上上传具有有限扩展名的文件。那么,如何验证我的图像字段仅适用于 jpg、bmp 和 gif。 另外,image字段默认采用哪个扩展名?
【问题讨论】:
标签: django django-models
这就是我的做法:
from django.utils.image import Image
# settings.py
# ALLOWED_UPLOAD_IMAGES = ('gif', 'bmp', 'jpeg')
class ImageForm(forms.Form):
image = forms.ImageField()
def clean_image(self):
image = self.cleaned_data["image"]
# This won't raise an exception since it was validated by ImageField.
im = Image.open(image)
if im.format.lower() not in settings.ALLOWED_UPLOAD_IMAGES:
raise forms.ValidationError(_("Unsupported file format. Supported formats are %s."
% ", ".join(settings.ALLOWED_UPLOAD_IMAGES)))
image.seek(0)
return image
也适用于 ModelForm。
单元测试:
from StringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test.utils import override_settings
from django.test import TestCase
class ImageFormTest(TestCase):
def test_image_upload(self):
"""
Image upload
"""
content = 'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00' \
'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
image = StringIO(content)
image.name = 'image.gif'
image.content_type = 'image/gif'
files = {'image': SimpleUploadedFile(image.name, image.read()), }
form = ImageForm(data={}, files=files)
self.assertTrue(form.is_valid())
@override_settings(ALLOWED_UPLOAD_IMAGES=['png', ])
def test_image_upload_not_allowed_format(self):
image = StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image.name = 'image'
files = {'image': SimpleUploadedFile(image.name, image.read()), }
form = ImageForm(data={}, files=files)
self.assertFalse(form.is_valid())
枕头会允许一堆image formats
【讨论】: