为什么只有在“static”文件夹中的图像才能显示?

YQ.*_*ang 5 html python flask

我正在构建一个图像识别 Flask 项目。我想要在网页上显示图像。这是我的项目的结构:

在此输入图像描述

如您所见,statictemplatesupload位于同一文件夹中。如果我将图像保存到static文件夹(由 VS2015 Flask 项目生成)中并编写result.html如下内容:

<!doctype html>
<h3>{{ outcome_info }}</h3>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="utf-8">
    <title>Flood Classifier</title>
</head>
<body> 
    <img src="{{url_for('static', filename=thename)}}">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当调用这个Python函数时,图像将成功显示:

@app.route('/classify', methods=['POST','GET'])
def classify():
    global image
    image = np.expand_dims(image, axis = 0)
    result = model.predict(image)
    if result[0][0] == 1:
        result = "flood"
    else:
        result = "no flood"
    return render_template('result.html', thename = imagename, outcome_info = result)
Run Code Online (Sandbox Code Playgroud)

但是,如果我将图像文件保存到upload(我自己创建的)中,然后更改文件夹名称,result.html如下所示:

<!doctype html>
<h3>{{ outcome_info }}</h3>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="utf-8">
    <title>Flood Classifier</title>
</head>
<body> 
    <img src="{{url_for('upload', filename=thename)}}">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

调用该 Python 函数时不会显示图像。图像必须保存到static文件夹中还是我误解了什么?

Kus*_*ikh 4

你可以使用这个配置:

from flask import Flask
app = Flask(__name__, static_url_path = "/upload", static_folder = "upload")
Run Code Online (Sandbox Code Playgroud)

然后您可以按如下方式访问您的图像:

<img src='/upload/image1.jpg' width="200" height="85">
Run Code Online (Sandbox Code Playgroud)

检查此答案以获取更多详细信息:Cannot show image from STATIC_FOLDER in Flask template