python flask在html页面上显示图像 [英] python flask display image on a html page

查看:7667
本文介绍了python flask在html页面上显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试传递图像的文件名并在模板上呈现它,
虽然我传递的实际名称没有显示在页面上

  @ 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)
返回render_template('start.html',profilepic_filename = profilepic_filename)

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

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

我也试过

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

两者都不起作用

解决方案

我在 static 文件夹中创建了 people_photo ,并放置了一个名为<$ c $的图片C> shovon.jpg 。从 application.py 我将图像作为变量传递给模板,并在模板中使用 img 标记显示它。 / p>

application.py

 来自flask进口Flask,render_template,request,url_for 
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')
返回render_template(index .html,user_image = full_filename)

index.html

 <!DOCTYPE html> 
< html>
< head>
< title> Index< / title>
< / head>
< body>
< img src ={{user_image}}alt =用户图片>
< / body>
< / html>

输出:




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}}
<img src="{{ url_for('data', filename='tim/img.jpg') }}"></img>

And I have also tried

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

Neither of which worked

解决方案

I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template.

In application.py:

from flask import Flask, render_template, request, url_for
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:

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

Output:

这篇关于python flask在html页面上显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆