Skip to content Skip to sidebar Skip to footer

Multiplefilefield Wtforms

class AddProductForm(FlaskForm): product_pictures = MultipleFileField('Pictures') submit = SubmitField('Add Pictures') def product_add_pics(): form = AddProduc

Solution 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.

Solution 2:

I know this question is old but I spent four hours banging my head against the wall trying to find a solution and finally figured it out with the help of an error code. MultiFileField will return the filenames as a string unless you specify the proper encoding in your form. simply add:

enctype="multipart/form-data"

to the HTML form tag and the original code will return

<class'werkzeug.datastructures.FileStorage'>

as expected.

Post a Comment for "Multiplefilefield Wtforms"