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")
3
Answers
The problem was with the encoding, at both the backend and frontend.
at flask
html
If you want to use bytes to draw an image, you should add
base64
to src tag.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:
And the corresponding HTML template: