Flask
Upload and display image in Flask

Upload and display image in Flask

A simple web application in Flask which will upload and display image.

We created ‘main.py’ for backend operation using flask. The ‘index.html’ file reside inside ‘templates’. The css file reside inside ‘staticFiles/main.css’. The uploaded file will be saved inside ‘staticFiles/uploads’.

The code for main.py

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

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

app = Flask(__name__,template_folder='templates',static_folder='staticFiles')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

#Define secret key to enable session
app.secret_key = "sanaan"

@app.route('/',methods=("POST","GET"))
def index():
    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 todatabase (defined uploaded folder in staticpath)
        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)
        #retriving uploaded file path from session
        img_file_path = session.get('uploaded_img_file_path',None)
    else:
        img_file_path = ""

    return render_template('index.html',user_image = img_file_path)


#Running the app
if __name__ == '__main__':
    app.run(port=5000,debug=True)

Code for index.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>
        <p style="color: blue;">Choose image file to upload</p>
        <img src="{{ user_image }}">

       
        
    </body>
</html>

Code for main.css

h1 {
    color: blue;
    font-size: 200%;
    text-align: center;
  }
  p {
    color: red;
    text-align: center;
    font-size: 100%;

  }
  img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 50%;
  }

form {
    display: table;
    margin: 0 auto;
}
  

Output: Landing Page

Output: After Uploading

Output: After Submission

Tags :