python - 将来自 flask send_file(ajax 响应)的图像显示到图像标签中

标签 python jquery ajax flask

如何显示来自 flask send_file ajax 响应的图像

HTML 文件


<button class="button" id="start">Start</button>

    <script>
        //start button click event

        $('#start').click(function() {
            $.ajax({
                url: 'http://127.0.0.1:5000/capture',
                type: 'GET',
                contentType: "image/jpg",
                success: function(result) {
                    document.getElementById('frame').src = 'data:image/jpg,' + result;
                }
            });
        });

flask


@app.route('/capture')
def capture_api():
    ...
    image_binary = img.read()

    return send_file(io.BytesIO(image_binary),
                     mimetype='image/jpeg',
                     as_attachment=True,
                     attachment_filename='%s.jpg' % "capture")

最佳答案

您必须将您的图像数据编码为 base64,并将其添加到您的 dom 中的图像元素。

我在 repl.it 中创建了一个示例应用程序:https://repl.it/@MichaelAnckaert/Flask-Playground

这是一个示例 Flask 应用程序:

from flask import Flask, render_template, make_response
import base64
app = Flask('app')

@app.route('/')
def hello_world():
  return render_template('image.html')


@app.route('/capture')
def capture_api():
  with open("house-thumbs-up.gif", "rb") as f:
    image_binary = f.read()

    response = make_response(base64.b64encode(image_binary))
    response.headers.set('Content-Type', 'image/gif')
    response.headers.set('Content-Disposition', 'attachment', filename='image.gif')
    return response

app.run(host='0.0.0.0', port=8080)

以及对应的HTML模板:

<img id="image">

<button class="button" id="start">Start</button>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"     integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
  let button = document.getElementById("start")
  button.addEventListener('click', () => {
    $.ajax({
        url: 'https://luminoustwincase--five-nine.repl.co/capture',
        type: 'GET',
        contentType: "image/jpg",
        success: function(result) {
          document.getElementById('image').src = 'data:image/gif;base64,' + result;
        }
    });
  });
</script> 

关于python - 将来自 flask send_file(ajax 响应)的图像显示到图像标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63921787/

相关文章:

python - 如何将二进制转换为数字?

python - 当 URL 中没有尾部斜杠时,使用 VueJS 单页的 Django 路由会出现意外行为

javascript - AngularJS 在 ng-click 上使用 ng-show 隐藏 div

javascript - JQuery - If ( $ ('#products' ).existOn.(document) ) == true {//这样做}

jquery - 将 JSON 从 python 脚本发送到 JQuery

javascript - 如何从远程服务器获取jsonp?

python - 如何在计算互补列表时正确处理重复项?

python - 替换非字母数字字符,除了一些异常(exception) python

javascript - 如果为空或使用ajax添加带值的逗号,如何将值附加到输入?

javascript - 使用 jQuery/JavaScript 更新一堆 HTML 元素的最有效方法?