首页 > 解决方案 > 在 index.html 中获取用户的表单输入后,如何将图像渲染到 display.html?

问题描述

我正在使用在我的机器(本地服务器)上运行的烧瓶应用程序。我想执行这个任务:

用户选择一个图像,该图像被渲染到一个模板。

我不想将图像文件上传到任何文件夹。根据用户如何选择图像并将其上传到不同的文件夹,许多问题得到了解答。

相反,我想做的就是从表单输入中获取图像并将其显示在浏览器中。

我参考了许多资源: 1. https://www.youtube.com/watch?v=Y2fMCxLz6wM 2.如何在 Flask 中将上传的图像传递给 template.html 3.从 HTML 表单中发布值并在其中访问它们烧瓶视图

但是,他们大多都提到在显示之前将图像上传到文件夹

这是我的 main.py


@app.route("/")
def index():
    return render_template('index.html')

@app.route("/display", methods=['POST', 'GET'])
def display():
    filename = request.form.get("file")
    return render_template("display.html", image_name=filename)

索引.html

<form id="display-img" action="http://localhost:5000/display" enctype=multipart/form-data method="POST">

<p>Image Select
        <input type="file" name="file" accept="image/*"></p> 

        <button>SUBMIT</button> 

</form>

显示.html

<body>
    {% extends "template.html" %}
    {% block content %}

    <h1> Displayed here </h1>

    <img id="blah" src=" {{ url_for('display', file=image_name)}}">

    {% endblock %}
    <script>

        function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function(e) {
            $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
        }

        $("#imgInp").change(function() {
        readURL(this);
        });
    </script>

实际输出为:

用户应该能够从文件夹 (index.html) 中选择图像。当我点击提交时,模板 display.html 正在呈现,但图像是损坏的链接图像符号

我期望的是:

用户应该能够从文件夹 (index.html) 中选择图像。当我点击提交时,它被渲染到显示页面(display.html)。

我尝试了不同的方法将图像名称变量传递给显示路径,但我仍然没有正确渲染图像。 到目前为止,这是渲染页面的外观

编辑:在 display.html 中添加了 JS 的代码

标签: javascripthtmlformsflaskrequest

解决方案


推荐阅读