python - 为什么只有 `static`文件夹下的图片才能显示?

标签 python html flask

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

enter image description here

如您所见,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>

调用此 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)

但是,如果我将图像文件保存到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>

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

最佳答案

你可以使用这个配置:

from flask import Flask
app = Flask(__name__, static_url_path = "/upload", static_folder = "upload")

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

<img src='/upload/image1.jpg' width="200" height="85">

查看此答案了解更多详情:Cannot show image from STATIC_FOLDER in Flask template

关于python - 为什么只有 `static`文件夹下的图片才能显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50831596/

相关文章:

python - 无法运行 Flask 文档中引用的示例代码

python - pandas:内部函数的错误参数(在 iterators.c 中)

java - 为什么与 Java 或 C# 中的相同算法相比,Python 中的素数筛如此慢?

python - 在 Pandas 中按特定月份和日期进行切片

javascript - 如何在滚动时关闭 JS/CSS 背景效果?

python - SQL中的x'0a'是什么意思?

python numpy round函数奇怪的错误

html - 将鼠标悬停在第 3 个上时更改 2 个 div 背景图像的不透明度?仅 HTML 和 CSS 还是我需要 JS?

javascript - jQuery :not() with parameter as value not working

python - Flask - 如何使用装饰器从 app.before_request 中排除路由?