[英]Flask Cannot Display Uploaded Images
我一直在关注多个 Flask 教程(但主要是这个)关于创建 web 应用程序,我可以用它来将图像读入 FastAi model。 在某些时候,我什至能够将图像上传到文件夹中,但无论我尝试做什么,我都无法让它们显示在网页本身上(重构 function,将文件夹移动到“静态”,显式声明路径等)。 我想我可能遗漏了一些非常基本的东西,但我对 Flask 以及 web 应用程序如何工作以知道那是什么知之甚少。
编辑:每次尝试通过“index.html”页面上传图像时,我都会收到 400 个错误请求页面,当我使用 Windows 资源管理器检查图像时,该图像不会出现在文件夹中。
file structure:
main.py
app
--> __init__.py
--> routes.py
主要.py:
from app import app
主要.py:
from flask import Flask
app = Flask(__name__)
from app import 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)
索引.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>
当引用 static 项目(如图像和文件)时,使用 static 文件夹来保存它们。
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 与您在 flask 后端路径中定义的内容保持一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.