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

3

6

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

Littman answered 20/4, 2021 at 4:22 Comment(0)
L
4

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.

Littman answered 20/4, 2021 at 4:22 Comment(0)
N
3

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
Nevski answered 7/7, 2022 at 17:29 Comment(0)
B
0

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

app.config['MAX_CONTENT_LENGTH'] = limit_in_mb * 1024 * 1024
Broadcasting answered 31/12, 2022 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.