Gokul NC
Gokul NC

Reputation: 1241

How to set file size limit in Flask-WTF's FileField?

How can I set FileSizeLimit validation for flask_wtf.file.FileField?

Upvotes: 6

Views: 1740

Answers (3)

77 ChickenNug
77 ChickenNug

Reputation: 49

The easiest method is to use app.config['MAX_CONTENT_LENGTH']

app.config['MAX_CONTENT_LENGTH'] = limit_in_mb * 1024 * 1024

Upvotes: 0

Gokul NC
Gokul NC

Reputation: 1241

We need to add a custom validator like this:

from wtforms.validators import ValidationError

def FileSizeLimit(max_size_in_mb):
    max_bytes = max_size_in_mb*1024*1024
    def file_length_check(form, field):
        if len(field.data.read()) > max_bytes:
            raise ValidationError(f"File size must be less than {max_size_in_mb}MB")
        field.data.seek(0)
    return file_length_check

Then pass the validator to the file uploader field like this:

uploaded_file = FileField('Upload your file', [FileRequired(), FileSizeLimit(max_size_in_mb=2)])

Credits:

Thanks to @yomajo for pointing out how to reset the filestream pointer after measuring the filesize.

Upvotes: 4

yomajo
yomajo

Reputation: 366

The above answer works to validate, but will fail when actually saving the file, due to exhausted file stream in size validation at len(field.data.read())

To save someone's hours, what I actually ended up with:

def FileSizeLimit(max_size_in_mb):
    max_bytes = max_size_in_mb*1024*1024

    def file_length_check(form, field):
        if len(field.data.read()) > max_bytes:
            raise ValidationError(
                f'File size is too large. Max allowed: {max_size_in_mb} MB')
        field.data.seek(0)
    return file_length_check

Upvotes: 3

Related Questions