【发布时间】:2020-12-09 22:24:38
【问题描述】:
刚刚开始使用 Python Flask 应用程序并使用 HTML。
我正在尝试构建一个简单的图片上传页面来显示上传的图片。我已经能够成功上传并保存文件,只是不显示它。 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Face with ID</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<h1>Upload Face (filename = face's name (i.e. John_Smith.jpg)</h1>
<hr>
<form action="/upload-image" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Select image</label>
<div class="custom-file">
<input type="file" class="custom-file-input" name="image"
id="image">
<label class="custom-file-label" for="image">Select image...</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
</div>
<img src="{{ uploaded_image }}">
</body>
</html>
烧瓶应用
import os
from flask import Flask, redirect, jsonify, request, url_for, render_template, flash
app = Flask(__name__)
app.config["IMAGE_UPLOADS"] = "C:/Flask/Upload/"
@app.route("/")
def home():
return render_template("index.html")
# Route to upload image
@app.route('/upload-image', methods=['GET', 'POST'])
def upload_image():
if request.method == "POST":
if request.files:
image = request.files["image"]
# print(image + "Uploaded to Faces")
# flash('Image successfully Uploaded to Faces.')
image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
filename = os.path.join(app.config["IMAGE_UPLOADS"], image.filename)
print("stored as:" + filename)
return render_template("upload_image.html", uploaded_image=filename)
return render_template("upload_image.html")
if __name__ == "__main__":
app.run()
我试图通过返回 render_template 并传递 upload_image=filename 创建一个单独的 html 来显示图像。
理想情况下,我只想在上传后在页面顶部或提交按钮下方显示上传的图片。
任何帮助将不胜感激。
【问题讨论】:
-
首先,您的
</body>标签放错了位置。 -
应该在
-
结束
<body>。它应该是模板中的倒数第二个标签,就在</html>的上方 -
对,所以我已将