Welcome to a tutorial on how to upload multiple files in Python Flask. So you need to upload multiple files in Flask, but have no idea how to get started? Here is a quick sharing and simple example – Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PYTHON FLASK MULTIPLE UPLOAD
All right, let us now walk through the steps of uploading multiple files in Python Flask.
QUICK SETUP
- Create a virtual environment
virtualenv venv
and activate it –venv\Scripts\activate
(Windows)venv/bin/activate
(Linux/Mac) - Install required libraries –
pip install flask werkzeug
- For those who are new, the default Flask folders are –
static
Public files (JS/CSS/images/videos/audio)templates
HTML pages
STEP 1) HTML UPLOAD FORM
<form action="http://localhost/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" multiple required>
<input type="submit" value="Upload!">
</form>
First, we start with an HTML file upload form. I don’t think this needs any explanation, it is just a <input type="file">
field that accepts multiple
files.
STEP 2) FLASK SERVER
2A) INIT
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
# (A2) FLASK SETTINGS + INIT
app = Flask(__name__)
HOST_NAME = "localhost"
HOST_PORT = 80
app.config["UPLOAD_FOLDER"] = "uploads/"
# app.debug = True
This section of the Flask server script should be self-explanatory too. We are just loading the required modules and defining a bunch of settings here.
2B) HTTP ROUTES
# (B) HTML UPLOAD PAGE
@app.route("/")
def index():
return render_template("S1_upload.html")
# (C) UPLOAD HANDLER
@app.route("/upload", methods = ["POST"])
def save_upload():
files = request.files.getlist("file")
# print(files)
for f in files:
filename = secure_filename(f.filename)
f.save(app.config["UPLOAD_FOLDER"] + filename)
return "UPLOAD OK"
Next, we define 2 “pages”.
/
To serve the HTML file upload form./upload
To handle the upload itself.- Use
files = request.files.getlist("file")
to get all of the uploaded files. - Then loop through the files
for f in files
. - Save them onto the server
f.save()
.
- Use
2C) START
# (D) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
Captain Obvious at your service. Start the Flask HTTP server.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
RESTRICTING FILE TYPES
HTML UPLOAD FORM
<form action="http://localhost/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required multiple accept="image/*">
<input type="submit" value="Upload!">
</form>
To restrict the accepted file types, the quick and easy way is to add a accept="MIME TYPE"
on the <input type="file">
itself.
FLASK SERVER
# DEFINE ALLOWED EXTENSIONS
ALLOWED_EXTENSIONS = {"txt", "pdf", "png", "jpg", "jpeg", "gif"}
# FUNCTION TO CHECK FILENAME
def allowed_file(filename):
return "." in filename and \
filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
# SAVE UPLOAD ONLY IF ALLOWED EXTENSION
if allowed_file(f.filename):
filename = secure_filename(f.filename)
f.save(app.config["UPLOAD_FOLDER"] + filename)
But the HTML file type restriction can be easily messed with, code ninjas can just change it in the developer’s console. So it’s safer to also include the file type check in Python itself, before we proceed to save the file on the server.
LINKS & REFERENCES
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
I love anime!!!