Python Flask 应用程序 - 上传图像并显示

Tho*_*YIT 1 html python flask

刚刚开始使用 Python Flask 应用程序并使用 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>

Run Code Online (Sandbox Code Playgroud)

烧瓶应用程序

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()
Run Code Online (Sandbox Code Playgroud)

我尝试通过返回 render_template 并传递 uploaded_image=filename 来创建一个单独的 html 来仅显示图像。

理想情况下,我只想在上传后将上传的图像显示在页面顶部或提交按钮下方。

任何帮助将非常感激。

在此输入图像描述

在此输入图像描述

GAE*_*fan 5

您的上传目录与视图不匹配。尝试这个:

@app.route('/upload-image', methods=['GET', 'POST'])
def upload_image():
    if request.method == "POST":
        if request.files:
            image = request.files["image"]
            image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
            return render_template("upload_image.html", uploaded_image=image.filename)
    return render_template("upload_image.html")


@app.route('/uploads/<filename>')
def send_uploaded_file(filename=''):
    from flask import send_from_directory
    return send_from_directory(app.config["IMAGE_UPLOADS"], filename)
Run Code Online (Sandbox Code Playgroud)

在您的模板中:

<img src="{{ url_for('send_uploaded_file', filename=uploaded_image) }}" />
Run Code Online (Sandbox Code Playgroud)