How can I set FileSizeLimit validation for flask_wtf.file.FileField
?
How to set file size limit in Flask-WTF's FileField?
Asked Answered
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.
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
The easiest method is to use app.config['MAX_CONTENT_LENGTH']
app.config['MAX_CONTENT_LENGTH'] = limit_in_mb * 1024 * 1024
© 2022 - 2024 — McMap. All rights reserved.