1

I am trying to display an image from a list of JPEG images into an HTML page. I tried to use the following code on flask :

from flask import Flask, render_template, request
from Daily_runs import func,func_2
import os
import glob


app = Flask(__name__)

@app.route('/')
def index():
    return render_template('Input.html')

@app.route('/hello', methods=['POST'])
def hello():
    path = request.form['path']
    func(path)
    func_2()
    images = glob.glob(os.path.join(path,'*.jpg'))
    image = os.path.abspath(images[0])


    return render_template('Image.html', user_image = image)

HTML template code :

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <img src={{user_image)}} alt="User Image">
</body>
</html>

The images does not get displayed instead only the alt text is displayed. Tried various other methods listed in this forum but could not succeed. Can anyone help on this ?

2
  • Please add code from your Daily_runs script. Commented Dec 13, 2018 at 12:48
  • the Daily runs script just creates a list of excel files and graphs in jpg format.Nothing else Commented Dec 13, 2018 at 13:16

2 Answers 2

3

To display images stored locally with flask and render_template, you must ensure that you save the desired images in a static/images folder in the parent directory of your application:

your_project_folder
|  - static/
      - images/
          - your_imagename.jpg
|  -templates
     - Image.html

   -main_app_file.py

Now, in your route:

import os
@app.route('/hello', methods=['POST'])
def hello():
   path = request.form['path']
   func(path)
   func_2()
   image = [i for i in os.listdir('static/images') if i.endswith('.jpg')][0]
   return render_template('Image.html', user_image = image)

In Image.html:

<img src='/static/images/{{user_image}}' alt="User Image">
Sign up to request clarification or add additional context in comments.

Comments

2

Have you tried putting the Jinja code within quotes in the html file?

i.e:

<img src="{{  user_image  }}" alt="User Image">

Also, it could just be a typo here, but there is an extra ")" in the image tag (removed above) which could be causing your issue.

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.