gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:36:42 25 4
gpt4 key购买 nike

如何显示来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com