My UploadForm class:
from app import app
from flask_wtf.file import FileRequired, FileAllowed
from wtforms.fields import MultipleFileField
from wtforms.validators import InputRequired,DataRequired
class UploadForm(FlaskForm):
.
.
.
roomImage = MultipleFileField('Room',validators=[FileAllowed(['jpg', 'png'], 'Image only!'), FileRequired('File was empty!')] )
.
.
.#there are other fields here which are not relevant to the problem at hand
HTML Template
{% extends "base.html" %}
{% block content %}
<h1>Upload Your Images</h1>
<form action="/" enctype="multipart/form-data" method="post" >
{{ form.csrf_token }}
Room<br />
{{form.roomImage()}}
.
.
. <MORE THINGS THAT I HAVE EDITED OUT>
{{form.submit()}}
<br/>
{% if form.errors %}
{{ form.errors }}
{% endif %}
</form>
{% endblock %}
hosts.py to run the check for validation
def upload_image():#NEEDS HEAVY FIXING
"""home page to return the web page to upload documents"""
form = UploadForm()
if form.validate_on_submit():
Using VS's debugging tools, I find that form.validate_on_submit() doesn't work and always fails validation and I get this error on my html page.
{'roomImage': ['File was empty!']}
There is another MultipleFileField control with almost the exact same code. This issue does not happen when I use FileField to upload one file. The documentation on this is very limited and all I had to go on was this. I don't really know how to solve this issue. I have searched extensively for finding example involving MultipleFileField but they are not using any validation. A thread on Github that I can't find anymore suggested using OptionalValidator, but then that is not an option for me and even that didn't work. Can someone suggest me a solution?
Even the FileAllowed() validator does not seem to work.
This works for me (found on GitHub "between the lines"):
multi_file = MultipleFileField("Upload File(s)", validators=[DataRequired()])
However
FileAllowed(["xml", "jpg"])
is ignored and does not work for me.
EDIT:
No, sadly, it does not work... It returns True for form.validate()
and for form.validate_on_submit()
but when you pass no files, by deleting
required=""
from
<input id="multi_file" multiple="" name="multi_file" required="" type="file">
and submit a form, it still evaluate that as True.
So problem sill persist in full, as described...
Regarding FileAllowed validator , it is not working because FileAllowed validator expect one FileStorage object , but MultipleFileField is sending a list of Filestorage objects , which is why it is not working . You have to implement a MultiFileAllowed validator yourself. For More details StackOverflow answer explained with example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With