【问题标题】:Flask Cannot Display Uploaded ImagesFlask 无法显示上传的图片
【发布时间】:2022-01-17 03:57:50
【问题描述】:

我一直在关注多个 Flask 教程(但主要是 this 一个)关于创建一个可用于将图像读入 FastAi 模型的 Web 应用程序。在某些时候,我什至能够将图像上传到文件夹中,但无论我尝试做什么,我都无法让它们显示在网页本身上(重构函数,将文件夹移动到“静态”,显式声明路径等)。我想我可能遗漏了一些非常基本的东西,但我对 Flask 以及 Web 应用程序的工作原理知之甚少,不知道那是什么。

编辑:每次尝试通过“index.html”页面上传图像时,我都会收到 400 个错误请求页面,而当我使用 Windows 资源管理器检查该图像时,该图像不会出现在文件夹中。

file structure:
main.py
app
--> __init__.py
--> routes.py

main.py:

from app import app

main.py:

from flask import Flask

app = Flask(__name__)

from app import routes

routes.py:

from app import app
import os
from fastai.vision.widgets import *
from flask import Flask, render_template, request

@app.route('/', methods=['GET','POST'])
def index():
    return render_template('index.html')

def get_predictions(img_path):
    global learner_inf
    learner_inf = load_learner('app/static/model/export.pkl')
    return learn_inf.predict(img_path)
    
@app.route('/predict', methods=['GET','POST'])
def predict():
    if request.method == 'POST':
        file = request.files['file']
        filename = file.filename
        file_path = os.path.join('app/static/uploads', filename)
        file.save(file_path)
        result = get_predictions(file_path)
    
    return render_template('predict.html', result = str(result), user_image = file_path) 

index.html

<!doctype html>
<html>
    <head>
        <title>Grocery Classifier</title>
    </head>
    <body>
        <h1>Grocery Classifier</h1>
        <form method="POST" action="/predict" enctype="multipart/form-data">
            <p><input type="file" name="file /"></p>
            <p><input type="submit" value="Submit"></p>
        </form>
    </body>
</html>

predict.html

<!doctype html>
<html>
    <head>
        <title>Grocery Classifier</title>
    </head>
    <body>
        <h1>Grocery Classifier</h1>
        <img src="{{ user_image }}" alt="Selected Image" class="img-thumbnail">
        <h2>{{ result }}</h2>
    </body>
</html>

【问题讨论】:

  • 你应该提供更多的输入,比如你得到了什么错误?您是否在 chrome 的开发者工具窗口中看到任何错误(如果您使用 chrome)?
  • 对于这个特定的代码,我在尝试上传图像(实际上并没有保存在任何地方)时收到一般的 400 Bad Request 错误。我在 bash 控制台中得到的只是 '"POST /predict HTTP/1.1" 400 -'。在页面上激活开发者模式对我没有任何帮助,我不知道如何进一步排除故障。

标签: python flask


【解决方案1】:

当引用图像和文件等静态项目时,请使用静态文件夹来保存它们。

app = Flask(__name__, static_folder="static")

之后,将其包含在 CSS/HTML 中。这不是在您的情况下插入图像的直接应用,但它是一个很好的例子。

 background-image: url("bg.gif");

引用图片的 url 可以是任何内容,请务必记住它以供以后参考。在 CSS 中看到的引用“bg.gif”会自动向“yoururl.com/bg.gif”发出 GET 请求以获取图像。 现在将该 url 链接到站点路径。

@app.route('/bg.gif', methods=['GET'])
def bghome():
    return send_from_directory("static", "bg.gif")

路径必须正确且准确,并且文件必须存在。如果您使用 kwarg 获取图像 url,请确保该 url 与您在烧瓶后端路径中定义的内容保持一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2014-07-25
    • 2013-01-02
    • 2019-05-13
    相关资源
    最近更新 更多