【问题标题】:python flask display image on a html page [duplicate]python flask在html页面上显示图像[重复]
【发布时间】:2018-03-28 20:54:54
【问题描述】:

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

@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 )

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

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

我也试过了

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

两者都不起作用

【问题讨论】:

    标签: python html flask flash-message


    【解决方案1】:

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

    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)
    

    index.html:

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

    输出:

    【讨论】:

    • 有没有其他人无法让它工作? pycharm 告诉我Process finished with exit code 0localhost:5000 没有显示任何图像
    • @frank, localhost:5000只要程序保持运行状态就可用。可能有什么东西停止了程序,你得到了Process finished with exit code 0
    • 我们如何显示来自 S3 链接的图像?任何帮助将不胜感激。
    • @vinitkantrod,它不在这个问题的范围内。如果您可以在 Flask 中创建一个关于 S3 存储桶图像使用的新问题,那就更好了。我认为未来的读者将会受益。
    • 有没有办法使用子文件夹而不是静态文件夹并通过local ressource错误?
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多