skip to Main Content

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


  1. Chosen as BEST ANSWER

    The problem was with the encoding, at both the backend and frontend.

    at flask

    image = b64encode(image_binary).decode("utf-8")
    return jsonify({'status': True, 'image': image})
    

    html

    document.getElementById('frame').src = 'data:;base64,' + result['image'];
    

  2. If you want to use bytes to draw an image, you should add base64 to src tag.

    document.getElementById('frame').src = 'data:image/jpg;base64,' + result;
    
    Login or Signup to reply.
  3. 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> 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search