How to upload multiple files with python flask¶
To upload multiple files, both frontend and backend are involved.
Frontend html¶
Aussume that the url /upload
handles uploading.
<form method="post" action="/upload" enctype="multipart/form-data">
<input multiple id="file" type="file" name="files"/>
<input type="submit"/>
</form>
Things you should notice about the html form above:
enctype
attribute of form must bemultipart/form-data
.- The file input element must have a
multiple
attribute so that multiple files can be uploaded in one time.
Backend flask¶
import os
from flask import request, redirect
from werkzeug.utils import secure_filename
@app.route('/upload', methods=('POST',))
def upload():
files = request.files.getlist('files')
for file in files:
fn = secure_filename(file.filename)
file.save(os.path.join(FILES_DIR, fn)) # replace FILES_DIR with your own directory
return redirect('/') # change to redirect to your own url
Things you should notice about the flask code above:
methods
must includePOST
- To get files, you must use
request.files.getlist('files')
instead ofrequest.files['files']
, because the latter is only used when uploading a single file. - use
secure_filename
to prevent malicious file name.
Drag and Drop to upload¶
Please refer to Upload multiple files using "drag and drop" with html5 and flask.
This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/flask_upload
Posted on 2022-04-01
Mail to author