【问题标题】:Go to an image after clicking on a link using Flask使用 Flask 单击链接后转到图像
【发布时间】:2020-10-29 21:24:16
【问题描述】:

我正在尝试以一种可以访问某些图像的方式制作网页,这些图像保存在“静态/图像”文件夹中,通过嵌入在它们各自名称下的超链接。我尝试在这样的页面中嵌入一个链接,但该网页有一个非常小的图标,没有显示图像。

<!DOCTYPE html>
<html>
     <body>
        <a href="/goto/Koala.png"> go </a>
     </body>
</html>
from flask import Flask, render_template,  session, redirect, request, url_for
import pandas as pd
import os

IMG_FOLDER = os.path.join('static', 'images')
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER

@app.route('/',methods=["GET"])  
def homePage():
    return render_template("index.html")

@app.route('/')
@app.route('/goto/<name>')
def show_index(name):
    file = name
    full_filename = os.path.join(app.config['IMG_FOLDER'], file)
    return render_template("goto.html", user_image = full_filename)

if __name__ == "__main__":
    app.run(debug=True)
<!DOCTYPE html>
<html>
<body>
    <img src="{{ user_image }}" alt="User Image">
</body>
</html>

相反,当我以下列方式使用它时,它显示得很好 -

from flask import Flask, render_template,  session, redirect, request, url_for
import pandas as pd
import os

IMG_FOLDER = os.path.join('static', 'images')
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER

@app.route('/',methods=["GET"])  
def homePage():
    return "hello"

@app.route('/')
@app.route('/goto')
def show_index():
    file = 'Koala.png'
    full_filename = os.path.join(app.config['IMG_FOLDER'], file)
    return render_template("goto.html", user_image = full_filename)

if __name__ == "__main__":
    app.run(debug=True)

我可能在某处做错了什么。任何帮助将非常感激。我正在尝试将这些名称以 for 循环的形式嵌入数据框中。无论如何,提前谢谢!

【问题讨论】:

    标签: python html image flask


    【解决方案1】:

    full_filename = os.path.join(app.config['IMG_FOLDER'], file) 将返回 static\images\file。但是,您需要的是:\static\images\file。因此,您需要运行的是:

    full_filename = "\\" + os.path.join(app.config['IMG_FOLDER'], file).

    或者,如果您想显示图像并有一个转到的链接,您可以执行以下操作:

    <!DOCTYPE html>
    <html>
        <body>
            <a href="/goto/{{user_image.split('\\')[3]}}">
                <img src="{{user_image}}" alt="User Image">
            </a>
        </body>
    </html>
    

    【讨论】:

    • 我非常感谢你给我看这个!谢谢,雅各布!
    猜你喜欢
    • 2019-07-06
    • 2016-03-13
    • 2014-05-12
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多