How do I display the image from a flask send_file ajax response
HTML file
<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")
You have to encode your image data as base64 and add it to an image element in your dom.
I've created a sample application in repl.it: https://repl.it/@MichaelAnckaert/Flask-Playground
Here's a sample Flask application:
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)
And the corresponding HTML template:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With