Send numpy array as bytes from python to JS through Flask Send numpy array as bytes from python to JS through Flask flask flask

Send numpy array as bytes from python to JS through Flask


If you don't set the MIME type explicitly, I think Flask will treat it as text data. Your browser seems to have decoded the binary data with ASCII, which can explain why only values larger than 127 were affected.

Therefore, please try setting the Content-Type of the response in Flask:

@app.route('/your/url/to/numpy/data')def get_nparray():    your_np_array = np.array([5.6], dtype=np.float32)    response = flask.make_response(your_np_array.tobytes())    response.headers.set('Content-Type', 'application/octet-stream')    # response.headers.set('Content-Disposition', 'attachment', filename='np-array.bin')    return response

Alternatively, there is a helper function flask.send_file to construct the response in a single line. Please find an example here.

Besides this error, also pay attention to the endianness of your binary data, which is hardware specific. I would refer you to this answer (Javascript Typed Arrays and Endianness).