【发布时间】:2021-11-19 10:59:06
【问题描述】:
编辑:
我解决了这个问题,但是由于问题被锁定,无法添加答案。
当将图像路径传递给使用flask 调用的html 文件时,flask 假定在调用应用程序的目录中存在一个名为static 的文件夹。就我而言,这是test_uploads/app。因此,要调用我的图像,我必须在此位置放置一个名为 static 的文件夹,其中包含我的图像文件:
test_uploads
├── app
│ ├─ templates
│ │ └─ image.html
│ ├─ static
│ │ └─ image.jpg
│ ├─ __init__.py
│ └─ routes.py
├── config.py
└── main.py
我从 html 文件中调用然后采用以下结构:
<!-- image.html -->
<!DOCTYPE html>
<html>
<head>
<title>View Stock</title>
</head>
<body>
<img src="static/{{ image }}">
</body>
瞧,图像渲染了。
可以使用app.config.static_folder 和app.config.static_url_path 属性操作此文件位置以适应您自己的位置。
这似乎是一个常见问题,我在这里查看了一些问题,但我无法让它工作。
我已将整个应用程序剥离回这个最基本的功能,但仍然无法让网页显示我的图像。
我得到的只是控制台中的错误图标和 404 错误。错误中给出的路径是我图像的正确路径,所以我更加困惑。
什么
我有以下文件结构,并试图在网页上显示 image.jpg:
test_uploads
├── app
│ ├─ templates
│ │ └─ image.html
│ ├─ __init__.py
│ └─ routes.py
├── cover_images
│ └─ image.jpg
├── config.py
└── main.py
<!-- image.html -->
<!DOCTYPE html>
<html>
<head>
<title>View Stock</title>
</head>
<body>
<img src="{{ image }}">
</body>
# __init__.py
from config import Config
from flask import Flask
app = Flask(__name__)
app.config.from_object(Config)
from app import routes, models
# config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config():
UPLOAD_FOLDER = os.path.join(basedir, 'cover_images')
# main.py
from app import app
# routes.py
from app import app
from flask import render_template
import os
@app.route('/check')
def image_check():
image_path = os.path.join(app.config['UPLOAD_FOLDER'], 'image.jpg')
print(image_path)
return render_template('image.html', image = image_path)
以及终端输出:
127.0.0.1 - - [19/Nov/2021 10:51:57] "GET /check HTTP/1.1" 200 -
127.0.0.1 - - [19/Nov/2021 10:51:57] "GET /Users/<me>/Downloads/test_uploads/cover_images/image.jpg HTTP/1.1" 404 -
【问题讨论】: