【问题标题】:How can I showcase all images in particular files with Flask?如何使用 Flask 展示特定文件中的所有图像?
【发布时间】:2025-11-22 15:40:02
【问题描述】:

我想用 Flask 做一个网页,它可以让我根据一些关键字搜索图片,并在网页中返回两张相关的图片。

并且,假设关键字是“史蒂夫·乔布斯”,这些与“史蒂夫·乔布斯”相关的图片将被 Google 搜索抓取并存储在名为“史蒂夫·乔布斯”的文件中。

但我仍然无法显示文件中的图像并返回空白页。

你好.py

@app.route("/about",methods=['GET', 'POST'])
def about():
    ...
    DIR = os.path.join(os.getcwd())
    DIR = os.path.join(DIR, query.split()[0])
    ...
    def show_index(): 
        for i,(img,Type) in enumerate(ActualImages[:2]):
            try:
                 req = urllib.request.Request(img, headers=header)
                 raw_img = urllib.request.urlopen(req).read()
                 cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
                 print(cntr)

                 if len(Type)==0:
                     f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+".jpg"),'wb')
                 else:
                      f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+"."+Type),'wb')
                      f.write(raw_img)
                      f.close()

            except Exception as e:
                  print('>>> Could not load: '+img)
                  print(e)

        return f

    return render_template('about.html', f = f)

关于.html

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

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    一个典型的 HTML 图像标签如下所示:

    <img src="/path/image.gif" alt="My Image"/>
    

    如您所见,src 属性包含一个 URL,告诉浏览器在哪里可以找到图像。它将关闭并从那里下载图像。它包含图像本身。您的代码似乎正在尝试将图像文件的内容加载到 HTML 中,但这是行不通的。

    (注意 - 可能将图像直接嵌入 HTML 中,但这很不寻常,所以我不会谈论它。)

    鉴于此,您需要将图像放在某处,并根据How do i link to images not in Static folder in flask 的答案提供和引用它们。

    【讨论】:

      最近更新 更多