在index.html中接受用户的表单输入后,如何将图像呈现到display.html?

时间:2019-07-11 00:28:22

标签: javascript html forms flask request

我正在使用在我的机器(本地服务器)上运行的flask应用程序。我要执行此任务:

用户选择一个图像,然后将该图像渲染为模板。

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

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

我提到了许多资源: 1. https://www.youtube.com/watch?v=Y2fMCxLz6wM 2. How to pass uploaded image to template.html in Flask 3. Post values from an HTML form and access them in a Flask view

但是,所有这些对象大多数都提到要在显示之前将图像上传到文件夹中

这是我的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)

index.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>

display.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)。

我尝试了不同的方法将图像名称变量传递到显示路径,但是仍然无法正确呈现图像。 This is how the rendered page looks so far

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

0 个答案:

没有答案