Upload and display image in Flask Python

To develop any Computer Vision web application image is must require. In this post, I will show you how to upload and display image in Flask. If you are new to Flask, I have written some basic tutorials for Flask with Python, you can definitely read those.

Must Read:

This tutorial is very much similar to my last post, where I showed you how to upload and display CSV files.

Create Template files

Let’s first list down what we want to achieve with this Flask web application:

  • Image uploading feature
  • Once image is uploaded successfully a message should show
  • Must have separate button, once clicked image should display in different page

So now let’s create a home page for our Flask Application. I am naming this HTML file “index_upload_and_display_image.html“.

index_upload_and_display_image.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Upload and display image in Flask</h1>
    <p>Show image in html using FLASK</p>

    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="uploaded-file" accept=".jpg">
        <input type="submit" value="Submit">
    </form>
  <br>
  <p style="color:blue;">Choose image file to upload</p>
  <form action="/show_data" target="_blank">
        <input type="submit" value="Show Image" />
    </form>
  </body>
</html>

In above code:

  • Line 10-13: Adding image upload form functionality
  • Line 16-18: Adding a button (named “Show Image“). If we click this button different page (http://127.0.0.1:5000/show_data) will open
  • Line 15: Adding string “Choose image file to upload” in blue color, it should change to green color once image is uploaded successfully
python flask file upload and download

Now if we upload any image and click the button “Submit” the message “Choose image file to upload” should change to “File uploaded successfully” in green color. To do this, we need to write another HTML file. Let’s name this HTML file “index_upload_and_display_image_page2.html

Also Read:  Django Basic login logout tutorial

index_upload_and_display_image_page2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Upload and display image in Flask</h1>
    <p>Show image in html using FLASK</p>

    <form method="POST" enctype="multipart/form-data" action="/">
        <input type="file" id="myFile" name="uploaded-file" accept=".png">
        <input type="submit" value="Submit">
    </form>
  <br>
  <p style="color:green;">File uploaded successfully</p>
  <form action="/show_image" target="_blank">
        <input type="submit" value="Display Image" />
    </form>
  </body>
</html>

Every line of the above code is same as “index_upload_and_display_image.html” except line 15 where we are changing the message to “File uploaded successfully

Note: In line 11, I have mentioned accepted file = png. You can change it to anything. We need to mention the accepted file extension in Flask code. That will be the actual accepted file extension.

flask display image from url

Now that we are done with our two home pages, let’s now write our Flask back-end code. I am naming this code as “flask_upload_display_image.py

flask_upload_display_image.py

from flask import Flask, render_template, request, session
import os
from werkzeug.utils import secure_filename

#*** Backend operation

# WSGI Application
# Defining upload folder path
UPLOAD_FOLDER = os.path.join('staticFiles', 'uploads')
# # Define allowed files
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

# Provide template folder name
# The default folder name should be "templates" else need to mention custom folder name for template path
# The default folder name for static files should be "static" else need to mention custom folder for static path
app = Flask(__name__, template_folder='templateFiles', static_folder='staticFiles')
# Configure upload folder for Flask application
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Define secret key to enable session
app.secret_key = 'This is your secret key to utilize session in Flask'


@app.route('/')
def index():
    return render_template('index_upload_and_show_data.html')

@app.route('/',  methods=("POST", "GET"))
def uploadFile():
    if request.method == 'POST':
        # Upload file flask
        uploaded_img = request.files['uploaded-file']
        # Extracting uploaded data file name
        img_filename = secure_filename(uploaded_img.filename)
        # Upload file to database (defined uploaded folder in static path)
        uploaded_img.save(os.path.join(app.config['UPLOAD_FOLDER'], img_filename))
        # Storing uploaded file path in flask session
        session['uploaded_img_file_path'] = os.path.join(app.config['UPLOAD_FOLDER'], img_filename)

        return render_template('index_upload_and_show_data_page2.html')

@app.route('/show_image')
def displayImage():
    # Retrieving uploaded file path from session
    img_file_path = session.get('uploaded_img_file_path', None)
    # Display image in Flask application web page
    return render_template('show_image.html', user_image = img_file_path)

if __name__=='__main__':
    app.run(debug = True)

Here in this code:

  • Line 16: Defining custom path for static and template files. If you are not mentioning this paths you may get error like: “image not showing“, “img src not working” etc.
  • Line 47: Showing image in “show_image.html” page. Note: the page location to display the image would be “127.0.0.1:5000/show_image” as per line 42 [@app.route(‘/show_image’)]
Also Read:  Add HTML and CSS in Flask Web Application

Note: If you are facing difficulties to understand the above codes, I will recommend you to read my previous posts:

Upload and Display CSV file in HTML table Flask Python
Add HTML and CSS in Flask Web Application
Beginners guide to Flask Python Web App framework

In line 47 we are storing full path of the uploaded image in a variable named “user_image” and displaying the image in “show_image.html” file. So we need to create an HTML file named “show_image.html“, where we need to call that “user_image” variable to display our uploaded image.

show_image.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href='/staticFiles/main.css' />
  </head>
  <body>
    <h1>Upload and display image in Flask</h1>
    <p>flask display image from uploaded folder</p>

<img src="{{ user_image }}" alt="Italian Trulli" width="500" height="400">
    </body>
</html>

Now let’s run our Flask code “flask_upload_display_image.py” to see the final output in browser.

Note: Before running this Flask code we need to create upload folder as mentioned in line 9 [UPLOAD_FOLDER = os.path.join(‘staticFiles’, ‘uploads’)]. As per this line, we have to create a folder named “uploads” inside our static folder “staticFiles”.

python flask upload image and display

Conclusion

In this post, I showed you how you can upload and display image in Flask with Python using GET POST method. In my next post, I will show you how you can create an Object Detection web application using this post.

Leave a Comment

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