how to upload multiple files using flask in python -
here code multiple files upload:
html code:
browse <input type="file" name="pro_attachment1" id="pro_attachment1" multiple>
python code:
pro_attachment = request.files.getlist('pro_attachment1') upload in pro_attachment: filename = upload.filename.rsplit("/")[0] destination = os.path.join(application.config['upload_folder'], filename) print "accept incoming file:", filename print "save to:", destination upload.save(destination)
but uploads single file instead of multiple files.
how to
in template, need add mulitple
attribute in upload input:
<form method="post" enctype="multipart/form-data"> <input type="file" name="photos" multiple> <input type="submit" value="submit"> </form>
then in view function, uploaded files can list through request.files.getlist('photos')
. loop list , call save() method on each item (werkzeug.datastructures.filestorage) save them @ given path:
import os flask import flask, request, render_template, redirect app = flask(__name__) app.config['upload_path'] = '\static\uploads' @app.route('/upload', methods=['get', 'post']) def upload(): if request.method == 'post' , 'photo' in request.files: f in request.files.getlist('photo'): f.save(os.path.join(app.config['upload_path'], f.filename)) return 'upload completed.' return render_template('upload.html')
furthermore, may need use secure_filename() clean filename:
# ... werkzeug.utils import secure_filename # ... f in request.files.getlist('photo'): filename = secure_filename(f.filename) f.save(os.path.join(app.config['upload_path'], filename)) # ...
you can generate random filename method.
full demo
view:
import os flask import flask, request, render_template werkzeug.utils import secure_filename app = flask(__name__) app.config['upload_path'] = '\static\uploads' @main.route('/upload', methods=['get', 'post']) def upload(): form = uploadform() if form.validate_on_submit() , 'photo' in request.files: f in request.files.getlist('photo'): filename = secure_filename(f.filename) f.save(os.path.join(app.config['upload_path'], filename)) return 'upload completed.' return render_template('upload.html', form=form)
form:
from flask_wtf import flaskform wtforms import submitfield flask_wtf.file import filefield, fileallowed, filerequired class uploadform(flaskform): photo = filefield('image', validators=[ filerequired(), fileallowed(photos, 'image only!') ]) submit = submitfield('submit')
template:
<form method="post" enctype="multipart/form-data"> {{ form.hidden_tag() }} {{ form.photo(multiple="multiple") }} {{ form.submit }} </form>
more
for better upload experience, can try flask-dropzone.
Comments
Post a Comment