Get Started with Multiple files Upload using Flask

Bala Murugan N G
Dev Genius
Published in
5 min readJun 28, 2020

--

Flask multiple files uploading

A Simple Guide to upload multiple files using Flask API and Python . . . ,

Photo by Nick Fewings on Unsplash

Why this tutorial?

After seeing many people writing blogs about “Flask for Beginners” tutorial. I’ve noticed that, only a less number of blogs that said about the “Flask File Uploading”. So, I took an interest on writing about the “Flask file Uploading”. I am sure this Blog walks you to build the File uploading that makes you simple. . . ,

In my previous blog, said about “Uploading a single file using python”

Now we will learn “How to send multiple files of data using Flask”. . . ,

Why Flask?

Django vs Flask is another age-old debate. Let’s deepdive in this,though people say Flask is simple and easy to get started with while Django is heavy for building web applications, there is another important reason why you should choose Flask over Django.

vectors by @pch-vector @iconicbestiary

Flask is like snorkeling whereas Django is scuba diving. Flask is light and easy whereas Django is capable of preparing you to enter deeper waters.

Flask is a widely used micro web framework for creating APIs in Python. It is a simple yet powerful web framework which is designed to get started quick and easy, with the ability to scale up to complex applications.

Django’s tag is, The web framework for perfectionist with a deadline. Because everything is built in, you don’t need to bother yourself with creating the files and thinking about how you should structure your app. It’s all ready for you and you can immediately get started with building your app (Prax).

It really depends on what you’re making, but if you’re building a simple app, consider Flask

From the documentation,

“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in micro framework means Flask aims to keep the core simple but extensible.

Requirements and Installation

  1. Of course, We need Python 3.5 or above. But why?? see this
  2. Install Flask
pip install flask

A Simple Flask Application

This step is for beginners, If you know the basics of Flask, skip this. . . ,

A simple Flask application to run. . ,

# app.pyfrom flask import Flask           # import flask
app = Flask(__name__) # create an app instance
@app.route("/") # at the end point /
def hello(): # call method hello
return "Hello World!" # which returns "hello world"
if __name__ == "__main__": # on running python app.py
app.run(host='0.0.0.0',port = 5000) # run the flask app

Run the Application by running “python app.py”. Go to browser and type “http://localhost:5000”, you will see“Hello World!” program is alive.

Get Started with Multiple Files Upload

File uploading is the process of transmitting the binary or normal files to the server. Flask facilitates us to upload the files easily.

The server-side flask script fetches the file from the request object using request.files[] Object. On successfully uploading the file, it is saved to the desired location on the server.

In this, we are going to upload a multiple “PNG” files and store them in a particular folder.

You can upload any file and store it as you wish. . . ,

Also you can use this to transfer files from one system to another one. . . ,

Create a file named “multiplefilesupload.py”

  1. Importing the Libraries
import os      # For File Manipulations like get paths, rename
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename

2. Create an Instance and check Extension

app=Flask(__name__)app.secret_key = "secret key" # for encrypting the session#It will allow below 16MB contents only, you can change it
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
path = os.getcwd()
# file Upload
UPLOAD_FOLDER = os.path.join(path, 'uploads')
# Make directory if "uploads" folder not exists
if not os.path.isdir(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDERALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

3. App routing and Application running

@app.route('/')
def upload_form():
return render_template('upload.html')


@app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':

if 'files[]' not in request.files:
flash('No file part')
return redirect(request.url)

files = request.files.getlist('files[]')

for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

flash('File(s) successfully uploaded')
return redirect('/')


if __name__ == "__main__":
app.run(host='127.0.0.1',port=5000,debug=False,threaded=True)

4. Template Creation

Create a Folder named “templates” and create a file ”upload.html” which should be inside the “templates” folder.

upload.html

<!doctype html><title>Python Flask Multiple Files Upload Example</title><h2>Select file(s) to upload</h2><p>{% with messages = get_flashed_messages() %}{% if messages %}<ul class=flashes>{% for message in messages %}<li>{{ message }}</li>{% endfor %}</ul>{% endif %}{% endwith %}</p><form method="post" action="/" enctype="multipart/form-data"><dl><p><input type="file" name="files[]" multiple="true" autocomplete="off" required></p></dl><p><input type="submit" value="Submit"></p></form>

Mind Waving??? Here is the full code

multiplefilesupload.py

upload.html

Running the Application

Run the Application by running “python multiplefilesupload.py”. Go to browser and type “http://localhost:5000”, you will see “upload files” in browser.

Flask Multiple files upload
Output of the Flask Multiple files uploads in “uploads” folder

If I upload different file rather than txt, pdf, png, jpg, jpeg, gif type of extension. The file will not be accepted . .,

Allowed file contents

The complete code is uploaded to the following GitHub repository

Single File Upload using Flask !!! checkout

Did you like what you read?

Hold the “clap” button and keep sharing

Thanks,

Bala Murugan N G

--

--