2

I am trying to send 2 pngs(or jpeg or any other format) images from my Flask server to my Reactjs front to display them there. I'm not sure how to encode this response though. The closest i've got is with people recommending to attach the images to a multipart form and send the form, but i can't quite figure out how to parse the form at the front since the response.data is a string.

I'm aware that this is likely not even the correct way to construct a multipart form on top of the it usually being used to send TO the server and not FROM, so i'll appreciate any corrections!

from flask import Flask, Response
from requests_toolbelt import MultipartEncoder


{...}

# getting the images
        bytes_object_rest = do_plot(rest_coordinate_arrays, rest_vcg_arrays)
        bytes_object_stress = do_plot(stress_coordinate_arrays, stress_vcg_arrays)

]
       mpencoder = MultipartEncoder(
            fields={'rest_graph': ('rest.png', bytes_object_rest, 'image/png'),
                    'stress_graph': ('stress.png', bytes_object_stress, 'image/png')},
            )

    return Response(mpencoder.to_string(), mimetype=mpencoder.content_type)

In the end, i'd like to know how to have a flask endpoint expose 2 .png plots to react and how to parse that response so i can render those 2 plots on the front. Thank you very much! [Here is the response from a call to this flask endpoint]

And here is response.data all stringified1

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
rtviii
  • 807
  • 8
  • 19

2 Answers2

2

In python encode the image to base64:

import base64

with open("yourfile.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

In js decode the image:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
Mykybo
  • 1,429
  • 1
  • 12
  • 24
  • thanks, dude! throw me another bone and tell me how to get to the 'data:image/png;base64,iVBORw0K...' part from the response.data? I see both images' hashes encoded in the response.data, but it looks like a single field with Content-Disposition: form-data; name="stress" being the only intelligeble part. – rtviii Jun 06 '19 at 14:35
1

I am trying to send 2 pngs(or jpeg or any other format) images from my Flask server to my Reactjs front to display them there.

Maybe this article could be helpful for you.

Your Flask server needs to expose a API where your React Frontend can then send data to.

Divide by Zero
  • 1,343
  • 1
  • 14
  • 37