Flask 无法显示上传的图像

问题描述 投票:0回答:2

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

编辑:每次我尝试通过“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>

预测.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>
python flask
2个回答
1
投票

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

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

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

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

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

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

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


0
投票
  1. 首先创建一个文件夹“static”
  2. 然后在其中创建您想要上传项目的文件夹,在您的情况下是“上传”

在main.py中上传

@app.route('/predict', methods=['GET','POST'])
def predict():
if request.method == 'POST':
    file = request.files['file']
    filename = file.filename
    file_path = os.path.join('uploads', filename)
    file.save(file_path)
    result = get_predictions(file_path)

阅读图像你只需更改为这个......:

<img src="{{ url_for('static', filename='uploads/' + userimage) }}" alt="{{ userimage }}">
© www.soinside.com 2019 - 2024. All rights reserved.