首页 > 解决方案 > 使用 Flask 无法正确显示图像

问题描述

我正在设置一个需要显示一些图像的应用程序。我的图像位于我的应用程序文件夹之外,这就是我使用它的原因:

    @app.route('/<path:filename>')
    def download_file(filename):
          return send_from_directory(MEDIA_FOLDER, filename=filename, as_attachment=True)

我的文件夹的架构是:

--images1
  |__ image1.png
  |__ image2.png
--images2
  |__ image3.png
  |__ image4.png
--web
  |__ app.py
  |__ templates
    |__ index.html

我已将所有图像路径存储在列表中:

images_path = ['image1.png', 'image2.png', ...]

目前,我尝试将图像显示为:

{% for image in images_path %}

<img src="{{ url_for('download_file', filename="{{ image }}") }}">

使用它,它总是显示相同的图像。在我的示例中,image1.png. 我试图检查 for 循环是否有效,并且有效。

我试过这个:

{{ image }} CHECKER
<img src="{{ url_for('download_file', filename="{{ image }}") }}">

它显示在我的页面上:

>>> 

image1.png CHECKER then the `image1.png`

image2.png CHECKER but also `image1.png`

更新 1

在我的 app.py 中,我添加了这个:

@app.route('/<path:filename>')
def download_file(filename):
images_folder = [images1, images2]
try:
    for image_folder in imagesfolder:
        MEDIA_FOLDER = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + str(image_folder) + "\\"
            return send_from_directory(MEDIA_FOLDER, filename=filename, as_attachment=True)
        except FileNotFoundError:
            abort(404)

在我的 template.html 上,我添加了这个:

{% for image in images_path %}

<img src="{{ url_for('download_file', filename=image) }}">

如何在此处正确设置路径?如何链接图像及其目录?


更新 2

我通过以下方式更改了我的脚本:

    @app.route('/<path:filename>')
    def download_file(filename):
        try:
            return send_file(filename, as_attachment=True)
        except FileNotFoundError:
            abort(404)

文件名将由以下内容定义:

>>>> filename = str(os.getcwd()) + str(list_machine[i]) + str(elem)

当我检查页面上的元素时,URL 似乎是正确的,但没有显示图像。


如何显示存储在我的文件夹中的所有图像?

提前致谢。

标签: pythonhtmlflask

解决方案


问题不是来自 {{ image }} 但我没有在您的代码 {% endfor %} 之后的 html img 中看到。

所以正确的代码是:

{% for image in images_path %}
<img src="{{ url_for('download_file', filename="{{ image }}") }}">
{% endfor %}

更新 1:

我认为您在代码中犯了几个错误:

@app.route('/<path:filename>')
def download_file(filename):
    images_folder = ['images1', 'images2']
    MEDIA_FOLDER = []
    try:
        for image_folder in imagesfolder:
            MEDIA_FOLDER.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + str(image_folder) + "\\")
                return send_from_directory(MEDIA_FOLDER, filename=filename, as_attachment=True)
    except FileNotFoundError:
        abort(404)

推荐阅读