Introduction

Here I am going to show you how to upload multiple images and display them one by one once images get uploaded. I am using here Flask as a web based framework on top of Python language.

On the UI (User Interface) we have input field which is used to select multiple files. To select multiple files after clicking on browse button you need to hold Ctrl key (Windows OS) on the keyboard.

Related Posts:

I have added some basic validation on file type, i.e., only image files will be uploaded. If you select non-image files then these files will not be uploaded. It will not throw any error in case non-image file but will not be uploaded.

Prerequisites

Python 3.8.3, Flask 1.1.2

Creating Project Directory

Create a project root directory called python-flask-upload-display-multiple-images as per your chosen location.

We may not mention the project’s root directory name in the subsequent sections but we will assume that we are creating files with respect to the project’s root directory.

Flask Configuration

We need flask instance in order to run web application using Flask framework.

We will also define our file upload location and maximum size of the file a user can upload.

We should not allow user to upload unlimited size of file due to security reasons or to avoid exhausting server space.

The standard directory for storing static resources such as images, css, javascript files into Flask application is to put under static directory. Here I am putting the uploaded file under static/uploads directory from where finally we will display the image on the web page.

Create a file called app.py with the below code.

from flask import Flask

UPLOAD_FOLDER = 'static/uploads/'

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

Upload Multiple Images

Next we will create main.py script to configure the endpoint for uploading multiple images. It defines the required URIs for performing file upload operations.

We have allowed certain types of images, such as png, jpg, jpeg, gif.

We are using http method POST to upload image files. after uploading and saving the image to disk we are returning the filename to the jinja2 flask template.

We have another function display_image() that is used on the flask template to display the actual images from the static/uploads folder.

This below line is required when you want to serve the file or image from static folder only.

return redirect(url_for('static', filename='uploads/' + filename), code=301)

We have used upload.html page for uploading multiple files to the desired directory.

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

ALLOWED_EXTENSIONS = set(['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_image():
	if 'files[]' not in request.files:
		flash('No file part')
		return redirect(request.url)
	files = request.files.getlist('files[]')
	file_names = []
	for file in files:
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file_names.append(filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
		#else:
		#	flash('Allowed image types are -> png, jpg, jpeg, gif')
		#	return redirect(request.url)

	return render_template('upload.html', filenames=file_names)

@app.route('/display/<filename>')
def display_image(filename):
	#print('display_image filename: ' + filename)
	return redirect(url_for('static', filename='uploads/' + filename), code=301)

if __name__ == "__main__":
    app.run()

Template View File

The default location in flask based applications of the template or view files is templates folder. This is upload.html page kept under templates directory.

<!doctype html>
<title>Python Flask Upload Multiple Images and Display them</title>
<h2>Select multiple images to upload and display</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>

{% if filenames %}
	{% for filename in filenames %}
		<div>
			<img src="{{ url_for('display_image', filename=filename) }}">
		</div>
	{% endfor %}
{% endif %}

Deploy the Application

Now navigate to the project’s root directory using command line tool and execute the command python main.py, your server will be started on default port 5000.

If you want to change the port then you can change the line app.run() to app.run(port=5001), where 5001 is the new port.

Test the Application

When you hit the URL http://localhost:5000 in the browser to get the below page to upload the image.

upload and display multiple images using python and flask

I selected two image files and uploaded for display on the page:

upload and display multiple images using python and flask

Source Code

Download

Thanks for reading.

Tags:

Leave a Reply

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