使用烧瓶在HTML页面上显示图像

时间:2018-12-13 08:54:45

标签: python html flask jinja2

我正在尝试将JPEG图像列表中的图像显示到HTML页面中。 我试图在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模板代码:

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

不显示图像,而是仅显示替代文本。 尝试了此论坛中列出的其他各种方法,但未成功。 有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

您是否尝试过将Jinja代码放在html文件的引号中?

即:

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

此外,这里可能只是拼写错误,但是图像标签中有一个额外的“)”(上面已删除),这可能引起您的问题。

答案 1 :(得分:0)

要显示使用flaskrender_template本地存储的图像,必须确保将所需的图像保存在应用程序父目录的static/images文件夹中:

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

   -main_app_file.py

现在,在您的路线上:

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)

Image.html中:

<img src='/static/images/{{user_image}}' alt="User Image">

答案 2 :(得分:0)

I tried as you said..Still the same problem:

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


app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

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


@app.route('/hello', methods=['POST'])
def hello():
    target = os.path.join(APP_ROOT,'static/images')
    path = request.form[r'path']
    func(path)
    func_2()
    image = [i for i in os.listdir(target) if i.endswith(".jpg")][0]
    return render_template('Image.html', user_image = image)
相关问题