1

I'm trying to render an image in html in flask, the path is pointing to the correct file but its not rendering some how.

#VIEWS

@inventory_bp.route("/show")
def show_image():
    id = 3
    image = Images.query.get(id)
    upload_folder = app.config['UPLOAD_FOLDER']
    image_path = os.path.join(upload_folder, image.filename)
    return render_template("image-upload.html",image_url=image_path)

#HTML

    <div>
      <img src="{{ image_url }}" alt="" />
    </div>
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'flaskbp/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

enter image description here

Sins97
  • 155
  • 1
  • 7
  • 1
    when i am debugging something like this i like to look at the generated html in chrome dev tools (shit + ctrl + j) so if you could update your question with a screen shot of the html when you go to the web page! – Phrase Feb 14 '23 at 06:47

1 Answers1

1

The image_path you're creating is the file path on your OS (e.g. C:\path\to\project\flaskbp\uploads\image.png. This is not the right src for the img element on your HTML.

Instead, you can place the uploads folder under the static folder, and then create the URL of the image dynamically.

from flask import Flask, render_template

app = Flask(__name__)


@app.route("/show")
def show_image():
    image_path = "uploads/image.png"
    return render_template("image.html", image_url=image_path)

<div>
    <img src="{{ url_for('static', filename=image_url) }}"/>
</div>

Folder structure:

\---root
    |   app.py
    |
    +---static
    |   \---uploads
    |           image.png
    |
    \---templates
            image.html
isshp
  • 292
  • 2
  • 9