Upload and display image using Python Flask


In this tutorial I will show you how to upload image and display on the web page once it is uploaded successfully. I have seen few tutorials on file uploads using Python Flask API but here I will show you how to allow users upload image file and display it on the browser once uploaded successfully.

Related Posts:


Python 3.8.3 – 3.9.1, Flask 1.1.2

Project Directory

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

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

Configure Flask Application

I will configure application through flask framework. I will also define our file upload location and maximum size of the file a user can upload.

You 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 you 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['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Configure Endpoint

Next I will create main.py script to configure the endpoint for uploading file or image. It defines the required URIs for performing file upload operations.

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

I am using http method POST to upload the image file. After uploading and saving the image to disk I am returning the filename to the jinja2 flask template.

I have another function display_image() that is used on the flask template to display the actual image 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)

I have used upload.html page for uploading file 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
def upload_form():
	return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_image():
	if 'file' not in request.files:
		flash('No file part')
		return redirect(request.url)
	file = request.files['file']
	if file.filename == '':
		flash('No image selected for uploading')
		return redirect(request.url)
	if file and allowed_file(file.filename):
		filename = secure_filename(file.filename)
		file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
		#print('upload_image filename: ' + filename)
		flash('Image successfully uploaded and displayed below')
		return render_template('upload.html', filename=filename)
		flash('Allowed image types are -> png, jpg, jpeg, gif')
		return redirect(request.url)

def display_image(filename):
	#print('display_image filename: ' + filename)
	return redirect(url_for('static', filename='uploads/' + filename), code=301)

if __name__ == "__main__":

View or Template File

Now you need template page for uploading file as well as it will also display the uploaded image. This is upload.html page kept under directory – templates, which is the standard directory for storing template or view file in flask application.

<!doctype html>
<title>Python Flask File Upload Example</title>
<h2>Select a file to upload</h2>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
	  {% endif %}
	{% endwith %}
{% if filename %}
		<img src="{{ url_for('display_image', filename=filename) }}">
{% endif %}
<form method="post" action="/" enctype="multipart/form-data">
			<input type="file" name="file" autocomplete="off" required>
		<input type="submit" value="Submit">

Image used in this application for uploading and displaying:

upload and display image using python flask

Deploying the Application

Now navigate to the project’s root directory using command line tool and execute the command python main.py or if your Python is on the classpath then just execute 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.

Testing 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 image using python flask

Once you select an image and upload then you will see the following screen:

upload and display image using python flask

Hope you got an idea how to upload and display image using Python Flask.


3 thoughts on “Upload and display image using Python Flask

Leave a Reply

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