Introduction

In this tutorial we will see how to upload image and display on the web page once it is uploaded successfully. We have seen few tutorials on file uploads using Python Flask API but here we will allow users only to upload image files.

Prerequisites

Python 3.8.1, Flask 1.1.1

Creating Project Directory

Create a project root directory called python-flask-upload-display-image 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.

Configuring Application

We will configure application through 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

Configuring Endpoint

Next we will create main.py script to configure the endpoint for uploading file or image. 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 the image file. 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 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)

We 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
	
@app.route('/')
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')
		return render_template('upload.html', filename=filename)
	else:
		flash('Allowed image types are -> png, jpg, jpeg, gif')
		return redirect(request.url)

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

View or Template File

Now we 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>
<p>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul class=flashes>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
		</ul>
	  {% endif %}
	{% endwith %}
</p>
{% if filename %}
	<div>
		<img src="{{ url_for('display_image', filename=filename) }}">
	</div>
{% endif %}
<form method="post" action="/" enctype="multipart/form-data">
    <dl>
		<p>
			<input type="file" name="file" autocomplete="off" required>
		</p>
    </dl>
    <p>
		<input type="submit" value="Submit">
	</p>
</form>

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, 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.

Download

Thanks for reading.

Tags:

Leave a Reply

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