1

Just getting started with Python Flask App and working with HTML.

I am trying to build a simple image upload page that will display the uploaded image. I have been able to successfully upload and save the file just not display it. HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Face with ID</title>
</head>
<body>

    <div class="container">
      <div class="row">
        <div class="col">

    <h1>Upload Face (filename = face's name (i.e. John_Smith.jpg)</h1>
          <hr>

    <form action="/upload-image" method="POST" enctype="multipart/form-data">

    <div class="form-group">
              <label>Select image</label>
              <div class="custom-file">
                <input type="file" class="custom-file-input" name="image"

    id="image">
                <label class="custom-file-label" for="image">Select image...</label>
              </div>
            </div>
    <button type="submit" class="btn btn-primary">Upload</button>
    </form>

        </div>
      </div>
    </div>

    <img src="{{ uploaded_image }}">

</body>
</html>

FLASK APP

import os

from flask import Flask, redirect, jsonify, request, url_for, render_template, flash

app = Flask(__name__)

app.config["IMAGE_UPLOADS"] = "C:/Flask/Upload/"


@app.route("/")
def home():
    return render_template("index.html")


# Route to upload image
@app.route('/upload-image', methods=['GET', 'POST'])
def upload_image():
    if request.method == "POST":
        if request.files:
            image = request.files["image"]
            # print(image + "Uploaded to Faces")
            # flash('Image successfully Uploaded to Faces.')
            image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
            filename = os.path.join(app.config["IMAGE_UPLOADS"], image.filename)
            print("stored as:" + filename)
            return render_template("upload_image.html", uploaded_image=filename)
    return render_template("upload_image.html")


if __name__ == "__main__":
    app.run()

I have tried to create a separate html for just displaying the image by returning the render_template and passing the uploaded_image=filename.

Ideally I would just like to display the uploaded image at the top of the page or below the submit button once uploaded.

Any help would be much appreciated.

enter image description here

enter image description here

8
  • First, your </body> tag is misplaced. Commented Aug 20, 2020 at 15:15
  • should it be below <form>? Commented Aug 20, 2020 at 15:39
  • That closes out the <body>. It should be the penultimate tag in the template, just above </html> Commented Aug 20, 2020 at 15:41
  • Right, so I have relocated the </body> to the line before </html> and tabbed accordingly but still no image is displayed. Commented Aug 20, 2020 at 16:17
  • <img src="/Faces/Chris_Beard.jpg" alt="Image Upload Display title"> Even with this statement The img is not displyed only the alt text. No errors... Commented Aug 20, 2020 at 16:34

2 Answers 2

6

You are not matching your uploads directory to the view. Try this:

@app.route('/upload-image', methods=['GET', 'POST'])
def upload_image():
    if request.method == "POST":
        if request.files:
            image = request.files["image"]
            image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
            return render_template("upload_image.html", uploaded_image=image.filename)
    return render_template("upload_image.html")


@app.route('/uploads/<filename>')
def send_uploaded_file(filename=''):
    from flask import send_from_directory
    return send_from_directory(app.config["IMAGE_UPLOADS"], filename)

In your template:

<img src="{{ url_for('send_uploaded_file', filename=uploaded_image) }}" />
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your help @GAEfan !! I ened up folloing this example roytuts.com/upload-and-display-image-using-python-flask BUT your answer is essentially the same, thanks again.
1

In case you just want to upload, analyze, and display the image without saving it to storage, i.e. api and edged image analysis, this example might be a guide for you. Flaskimio

@app.route("/",methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' not in request.files:
            print('No file attached in request')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            print('No file selected')
            return redirect(request.url)
        if file and check_allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print(filename)
            img = Image.open(file.stream)
            with BytesIO() as buf:
                img.save(buf, 'jpeg')
                image_bytes = buf.getvalue()
            encoded_string = base64.b64encode(image_bytes).decode()         
        return render_template('index.html', img_data=encoded_string), 200
    else:
        return render_template('index.html', img_data=""), 200


<form method="post" enctype="multipart/form-data">
    <p><input type="file" id="file" name="file"><input type=submit value=Upload></p>
    <img src="data:image/jpeg;base64,{{ img_data }}" id="img-upload" alt="img_data" class="img-upload"/>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.