Maximum image size when downloading a file

I have an ImageField in my form. How can I apply the file size min / max, something like -

image = forms.ImageField(max_size = 2MB) 

or

 image = forms.ImageField(min_size = 100k) 

Thank.

+40
django image-processing django-forms
Jun 01. '11 at 2:00
source share
3 answers

models.py

 class Product(models.Model): image = models.ImageField(upload_to="/a/b/c/") 

forms.py

 class ProductForm(forms.ModelForm): # Add some custom validation to our image field def clean_image(self): image = self.cleaned_data.get('image', False) if image: if image._size > 4*1024*1024: raise ValidationError("Image file too large ( > 4mb )") return image else: raise ValidationError("Couldn't read uploaded image") 
+48
Jun 01 2018-11-11T00:
source share

This is essentially a duplicate of Django's file upload size limits.

You have two options:

  • Use validation in Django to verify the size of the downloaded file. The problem with this approach is that the file must be fully downloaded before it is checked. This means that if someone uploads a 1 TB file, you will probably run out of hard drive before the user gets a form error.

  • Configure the web server to limit the allowed upload body size. for example, if you are using Apache, set the LimitRequestBody parameter. This will mean that if the user tries to load too much, they will get an error page that is configured in Apache

As @pastylegs says in the comments, using a combination of both is probably the best approach. Suppose you want a maximum of 5 MB, perhaps you apply a 20 MB limit at the web server level and a 5 MB limit at the Django level. The 20 MB limit will provide some protection against malicious users, and the 5 MB limit in Django provides good UX.

+44
Jun 01 2018-11-11T00:
source share

Here is another option that I have not seen in variations of this question in stackoverflow: use your own validator in your models. If you use this method and ModelForm in forms.py, then that should be all you need.

models.py

 from django.core.exceptions import ValidationError class Product(models.Model): def validate_image(fieldfile_obj): filesize = fieldfile_obj.file.size megabyte_limit = 5.0 if filesize > megabyte_limit*1024*1024: raise ValidationError("Max file size is %sMB" % str(megabyte_limit)) image = models.ImageField(upload_to="/a/b/c/", validators=[validate_image]) 
+19
Jan 05 '14 at 22:59
source share



All Articles