0

I am trying to send an image from the flask server to the web script. The first server connects to another API and gets an image. I don't want to save this image just forward it to the web application script.

@app.route('/api/image', methods=['GET'])
def return_image():
    r = requests.get(f"{api_url}/image")
    return send_file(
    BytesIO(r.content),
    mimetype='image/jpeg',
    as_attachment=True,
    attachment_filename='test.jpg')

I am trying to get this image by ajax request and display it.

function updateImage() {
  $.ajax({
    url: "/api/image",
    type: "GET",
    dataType: 'image/jpg',
    success: function (res) {
      $(theImg).attr("src", 'data:image/png;base64,'+ res);
      M.toast({
        html: 'Loading image: Success'
      })
    },
    error: function () {
      M.toast({
        html: 'Loading image: Fail'
      })
    }
  });
}

I tried to make this work but wasn't able to. I really appreciate your help.

1 Answers1

0

At a glance your JS writes a data-uri to the src attribute, but res is actually the binary data with a image/png mimetype.

So you either need to base64 encode r.content on the server side, here's an example which actually creates the entire uri server side, then return that string and have your JS add that to the src attribute.

Or if you just want make your JS support the exisitng endpoint you could probably create a blob based on /api/image response, then write that to the img tag.

v25
  • 5,206
  • 2
  • 13
  • 24