Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

python - MultipleFileField wtforms

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...