Python Image Upload using Flask Example

Published On: 11/06/2022 | Category: Python

Hi Dev,

In this example, you will learn upload image using flask python. step by step explain python image upload using flask app. you'll learn python image upload using flask and python. you can see how to upload image file in flask. Follow bellow tutorial step of python image upload using flask.

Here I will show you how to allow users upload image file and display it on the browser once uploaded successfully.

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/files directory from where finally you will display the image on the web page.

So let's see the below example:


Next I will create script to configure the endpoint for uploading file or image. It defines the required URIs for performing file upload operations.
from flask import Flask, render_template, session, flash
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField
from werkzeug.utils import secure_filename
import os
from wtforms.validators import InputRequired

app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'
app.config['UPLOAD_FOLDER'] = 'static/files'

class UploadFileForm(FlaskForm):
    file = FileField("File", validators=[InputRequired()])
    submit = SubmitField("Upload File")

@app.route('/', methods=['GET',"POST"])
@app.route('/home', methods=['GET',"POST"])
def home():
    form = UploadFileForm()
    if form.validate_on_submit():
        file = # First grab the file,app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) # Then save the file

        session['name'] = 'Image Upload Successfully'

    return render_template('index.html', form=form)

if __name__ == '__main__':
Create a View File

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

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <script src="[email protected]/dist/jquery.slim.min.js"></script>
    <script src="[email protected]/dist/umd/popper.min.js"></script>
    <script src="[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4>Python Image Upload Using Flask Example -</h4>
                    <div class="card-body">
                        {% for mess in get_flashed_messages()  %}
                          <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close" class="fade close">
                              <span aria-hidden="true">×</span>
                          {% endfor %}
                        <form method='POST' enctype='multipart/form-data'>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="file" name="file" required>
                                <label class="custom-file-label" for="file">Choose file</label>
                            <div class="col-md-12 mt-3 text-center">
                                <button type="submit" class="btn btn-success">Submit</button>

// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
  var fileName = $(this).val().split("\\").pop();
Run Example

It will help you....