python flask在html页面上显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46785507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:50:47  来源:igfitidea点击:

python flask display image on a html page

pythonhtmlflaskflash-message

提问by Darren rogers

I am trying to pass a filename of an image and render it on a template, Although I am passing the actual name through it does not display on the page

我正在尝试传递图像的文件名并将其呈现在模板上,尽管我通过它传递了实际名称并没有显示在页面上

@app.route('/', methods=['GET','POST'])
@app.route('/start', methods=['GET','POST'])
def start():
person_to_show = 'tim'
profilepic_filename = os.path.join(people_dir, person_to_show, "img.jpg")
return render_template('start.html',profilepic_filename  =profilepic_filename )

For example: profilepic_filename = /data/tim/img.jpg I have tried

例如: profilepic_filename = /data/tim/img.jpg 我试过了

{{profilepic_filename}}
<img src="{{ url_for('data', filename='tim/img.jpg') }}"></img>

And I have also tried

我也试过

<img src="{{profilepic_filename}}"></img>

Neither of which worked

两者都不起作用

回答by arsho

I have created people_photoin staticfolder and placed an image named shovon.jpg. From the application.pyI passed the image as variable to template and showed it using imgtag in the template.

people_photostatic文件夹中创建并放置了一个名为shovon.jpg. 从application.py我将图像作为变量传递给模板并使用img模板中的标签显示它。

In application.py:

application.py

from flask import Flask, render_template
import os

PEOPLE_FOLDER = os.path.join('static', 'people_photo')

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER

@app.route('/')
@app.route('/index')
def show_index():
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'shovon.jpg')
    return render_template("index.html", user_image = full_filename)

In index.html:

index.html

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

Output:

输出:

enter image description here

在此处输入图片说明