Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wtforms, Multi selection file upload

I have a form contains name and pictures

MyForm:

    name = TextField(
    u'name',
    validators=[
        validators.DataRequired(),
        validators.Length(min=1, max=25)
    ]
)   

    pictures = FileField(
    u'pictures',
    validators=[
        FileRequired(),
        FileAllowed(['jpg', 'png'], 'Images only!')
    ]
)

Jinja2 template:

{% from "_form_helpers.tpl" import render_field %}
<form method="post" action="" enctype="multipart/form-data">
  <dl>
    {{ render_field(form.name) }}
    {{ render_field(form.pictures) }}
  </dl>
  <p>{{ form.submit }}
</form>

I want to upload one or more picture in a single field (Multi selection).

How to do this?

Thanks..

like image 560
Anas Aldrees Avatar asked May 17 '14 00:05

Anas Aldrees


1 Answers

You need to specify the multiple attribute for the input tag. This can be done in your templates like so:

form.pictures(multiple="")

which will result in your generated html allowing for multiple file selection:

<input id="pictures" multiple name="pictures" type="file">

How to Manipulate multiple files using request.files:

    images = request.files.getlist("pictures")
    if images:
        for img in images:
            # Create Images
            file_name = str(uuid.uuid4()) + secure_filename(img.filename)
            image_file = os.path.join(app.config['UPLOAD_FOLDER'], file_name)
            img.save(image_file)

            # Save record
            image = models.Image(record_id=record.record_id,
                                 file_name=file_name.encode('utf-8'))
            db.session.add(image)

    db.session.commit()
like image 81
Mark Galloway Avatar answered Nov 03 '22 00:11

Mark Galloway