[英]Display image on HTML page using flask
我正在嘗試將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>
不會顯示圖像,而只會顯示替代文本。 嘗試了此論壇中列出的其他各種方法,但未成功。 有人可以幫忙嗎?
您是否嘗試過將Jinja代碼放在html文件的引號中?
即:
<img src="{{ user_image }}" alt="User Image">
另外,這里可能只是拼寫錯誤,但是圖像標記中有一個額外的“)”(上面已刪除),這可能會導致您的問題。
要顯示使用flask
和render_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">
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.