【问题标题】:Why is my local file not being found by my HTML code? [duplicate]为什么我的 HTML 代码找不到我的本地文件? [复制]
【发布时间】: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_folderapp.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 -

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    尝试在其余部分之前添加./

    【讨论】:

    • image_path = './' + image_path 这并不能解决它
    【解决方案2】:

    应该是这样的 “../image.jpg”

    【讨论】:

    • 实际的代码确实指向了正确的文件名——我在这里更改了它以使其更清晰,但理论上一切都指向正确的位置
    猜你喜欢
    • 2019-12-19
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多