Uploaded files are available in request.files
, a MultiDict
mapping field names to file objects. Use getlist
— instead of []
or get
— if multiple files were uploaded with the same field name.
request.files['profile'] # single file (even if multiple were sent)
request.files.getlist('charts') # list of files (even if one was sent)
The objects in request.files
have a save
method which saves the file locally. Create a common directory to save the files to.
The filename
attribute is the name the file was uploaded with. This can be set arbitrarily by the client, so pass it through the secure_filename
method to generate a valid and safe name to save as. This doesn't ensure that the name is unique, so existing files will be overwritten unless you do extra work to detect that.
import os
from flask import render_template, request, redirect, url_for
from werkzeug import secure_filename
# Create a directory in a known location to save files to.
uploads_dir = os.path.join(app.instance_path, 'uploads')
os.makedirs(uploads_dir, exists_ok=True)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# save the single "profile" file
profile = request.files['profile']
profile.save(os.path.join(uploads_dir, secure_filename(profile.filename)))
# save each "charts" file
for file in request.files.getlist('charts'):
file.save(os.path.join(uploads_dir, secure_filename(file.name)))
return redirect(url_for('upload'))
return render_template('upload.html')