问题
class AddProductForm(FlaskForm):
product_pictures = MultipleFileField('Pictures')
submit = SubmitField('Add Pictures')
def product_add_pics():
form = AddProductForm()
if form.validate_on_submit():
if form.product_pictures.data:
for picture_upload in form.product_pictures.data:
print(type(picture_upload))
form:
<div class="form-group">
{{ form.product_pictures.label() }}
{{ form.product_pictures(class="form-control-file") }}
{% if form.product_pictures.errors %}
{% for error in form.product_pictures.errors %}
<span class="text-danger">{{ error }}</span>
{% endfor %}
{% endif %}
</div>
I always got type as string. How can I get the binary files? I use MultipleFileField from the wtforms.
回答1:
The documentation for the FileField
class specifically says the following about handling file contents:
By default, the value will be the filename sent in the form data. WTForms does not deal with frameworks’ file handling capabilities.
This same thing applies to the MultipleFileField
class as well.
What this means is that you will have to ask flask
for those files. And, the quickest way to do that is to use the request.files
for the request you are handling.
In sum, you will need to rewrite your product_add_pics
function to grab the files from the request
object, as follows:
from flask import request
def product_add_pics():
form = AddProductForm()
if form.validate_on_submit():
pics = request.files.getlist(form.product_pictures.name)
if pics:
for picture_upload in pics:
picture_contents = picture_upload.stream.read()
print(type(picture_contents))
# Do everything else you wish to do with the contents
You'll notice the usage of request.files.getlist
here. This is important since you're using a MultipleFielField
class to accept multiple files. Using .getlist
allows you to retrieve all the files the end user selected from their machine.
And finally, to get the bytes contained in each file, you will need to get the stream
of each file and read
it. That should yield the bytes you're looking for.
I hope this proves useful.
来源:https://stackoverflow.com/questions/53021662/multiplefilefield-wtforms