【发布时间】: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 -'。在页面上激活开发者模式对我没有任何帮助,我不知道如何进一步排除故障。