Python Flask Multiple Files Upload Example

Multiple Files Upload

The tutorial, Python flask multiple files upload example, will show you how to upload multiple files using Python and Flask technologies. You may also find useful example on file upload on different technologies.

Related Posts:

Prerequisites

Python 3.6.6/3.11.5, Flask 1.1.1/2.3.3

File Upload Implementation

Please go through the following steps in order to implement Python flask multiple files upload example.

Step 1. Create the below app.py script(py is the extension to indicate Python script) where I have imported the flask module. Notice how I have created flask instance. Here I need to assign secret key otherwise flash will not work in Python.

In the below script we import the required module – Flask. If you do not have this module then install it.

Here I have also specified the file upload folder and maximum size of the file to be uploaded as 16MB.

from flask import Flask

UPLOAD_FOLDER = 'D:/uploads'

app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Step 2. Next I have created main.py script. This script is the perfect instance of Python flask file upload example. It defines all required URIs for performing file upload operations.

I have used upload.html page for uploading file to the desired directory.

I will show success message on successful file upload.

import os
#import magic
import urllib.request
from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename

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':
        # check if the post request has the files part
		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()

Step 3. Now I need a template page for uploading file. This is upload.html page kept under subdirectory – templates. You can use this page for uploading single or multiple files. If you want to upload multiple files then you need to hold CTRL key and select files.

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

Testing the Files Upload Application

When you open the default URL http://localhost:5000 then you will see below page:

python flask multiple file upload example

When files successfully get uploaded to the destination directory:

python flask multiple file upload example

Source Code

Download

2 thoughts on “Python Flask Multiple Files Upload Example

  1. I am getting this error :
    View function mapping is overwriting an existing endpoint function: upload_form

    Could you please suggest where to change the endpoint

  2. Hi Roy,
    Thanks so much for providing this tutorial. This is just what I was looking for. The problem I am facing is that when I run the solution from visual studio, it builds file, but when I click the upload button I get a 500 Internal Server Error and I get the error message below.

    filename = secure_filename(file.filename)
    NameError: name ‘secure_filename’ is not defined

    Can you advise?

    Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *