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:

Example

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.

main.py
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 = form.file.data # First grab the file
        file.save(os.path.join(os.path.abspath(os.path.dirname(__file__)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) # Then save the file

        session['name'] = 'Image Upload Successfully'
        flash(f"{session['name']}")

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

if __name__ == '__main__':
    app.run(debug=True)
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.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <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="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <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 - Tuts-Station.com</h4>
                    </div>
                    <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>
                            </button>
                            {{mess}}
                            </div>
                          {% endfor %}
                        <form method='POST' enctype='multipart/form-data'>
                            {{form.hidden_tag()}}
                            <label>Image:</label>
                            <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>
                            <div class="col-md-12 mt-3 text-center">
                                <button type="submit" class="btn btn-success">Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script>
// 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();
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>
</body>
</html>
Run Example
python3 main.py
Output:

It will help you....