1

I have a Django app where users can upload images to an S3 bucket, and I tested it with a few users and found out that many uploaded very large photos (up to 55 MB) and when I render the main page, all the images must be displayed. Each time someone browses it, it drains my bandwidth.

Is there a way to limit the size of the image people upload? Perhaps to 10 MB each?

etnguyen03
  • 580
  • 4
  • 19
MartinD
  • 21
  • 3

1 Answers1

2

You could do something like this - perhaps in a validators.py:

from django.core.exceptions import ValidationError


def validate_file_size(value):
    filesize = value.size
    
    if filesize > 10485760:  # 10 MiB in bytes
        raise ValidationError("The maximum file size that can be uploaded is 10 MiB")
    else:
        return value

and then in your models.py:

from .validators import validate_file_size

file = models.FileField(..., validators=[validate_file_size])

However, this is server side, not client side. Therefore, each submission of the file transmits the file over the wire to you, resulting in bandwidth charges. If someone was to upload a 1 GiB file, then the upload would consume 1 GiB of bandwith, even if it is rejected by the server.

Client-side validation would require some JS like this, but you would also need server-side validation.

etnguyen03
  • 580
  • 4
  • 19
  • Thank you very much, is their a way to make a kind of: if filesize > 10mb: resize the image to 10mb ?? the problem is not really that the user upload big photos it s that i renders those every time i render the gallery because i didn't plan for this kind of situation and i didn't add a "create thumbnail" function and i have no idea how to add it now ... sorry i only started programming a few months ago and my knowledge is still very basic – MartinD Dec 08 '20 at 19:27
  • You could use Pillow [like this](https://pillow.readthedocs.io/en/stable/reference/Image.html#create-thumbnails), but you have to be careful because if someone uploads a non-image, it could (_could!_) expose you to arbitrary code execution vulnerabilities. – etnguyen03 Dec 08 '20 at 19:32
  • Thank you very much ! – MartinD Dec 09 '20 at 17:25