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

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

 

QUICK NOTES

  • Create a project folder, e.g. D:\up, unzip the code inside this folder.
  • Navigate to the project folder in the command line cd D:\up, create a virtual environment to not 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

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.

 

STEP 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.

 

STEP 2) FLASK SERVER

2A) INIT

S2_server.py

# (A) INIT# (A1) LOAD MODULESfrom flask import Flask, render_template, requestfrom werkzeug.utils import secure_filename # (A2) FLASK SETTINGS + INITapp = Flask(__name__)HOST_NAME = "localhost"HOST_PORT = 80app.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 [email protected]("/")  def index():  return render_template("S1_upload.html") # (C) UPLOAD [email protected]("/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) STARTif __name__ == "__main__":  app.run(HOST_NAME, HOST_PORT)

Captain Obvious at your service. Start the Flask HTTP server.

 

 

EXTRA 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 EXTENSIONSALLOWED_EXTENSIONS = {"txt", "pdf", "png", "jpg", "jpeg", "gif"} # FUNCTION TO CHECK FILENAMEdef allowed_file(filename):  return "." in filename and \    filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS # SAVE UPLOAD ONLY IF ALLOWED EXTENSIONif 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!

Xổ số miền Bắc