Get Started with Multiple files Upload using Flask

Get Started with Multiple files Upload using Flask

Photo by Nick Fewings on Unsplash

Why this tutorial?

Why Flask?

vectors by @pch-vector @iconicbestiary

Requirements and Installation

pip install flask

A Simple Flask Application

# app.py

from 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

Get Started with Multiple Files Upload

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

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_FOLDER

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@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)

<!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

Running the Application

Flask Multiple files uploadOutput of the Flask Multiple files uploads in “uploads” folder

Allowed file contents