Upload Multiple Files In Python Flask (Simple Example)

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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Flask Upload Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create your own project folder, e.g. D:\up, unzip the code inside this folder.
  • Open the terminal (or command line), navigate to your project folder cd D:\up.
  • As usual, create a virtual environment if you don’t want to mess up your other projects.
    • virtualenv venv
    • Windows – venv\scripts\activate
    • Mac/Linux – venv/bin/activate
  • Get all the required packages – pip install Flask werkzeug
  • Launch! python s2_server.py and access http://localhost.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PYTHON FLASK MULTIPLE UPLOAD

All right, let us now walk through the steps of uploading a file in Python Flask.

 

PART 1) HTML UPLOAD FORM

templates/s1_upload.html
<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.

 

PART 2) FLASK SERVER

2A) INIT

s2_server.py
# (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

s2_server.py
# (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().

 

2C) START

s2_server.py
# (D) START
if __name__ == "__main__":
  app.run(HOST_NAME, HOST_PORT)

Lastly, Captain Obvious at your service, this starts the Flask HTTP server.

 

 

USEFUL BITS & LINKS

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

templates/s1_upload.html
<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

s2_server.py
# 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!

Leave a Comment

Your email address will not be published.