I am currently researching the possibility of reading partial XHR responses with binary data. Our current approach is based on the 'responseText' property and base64 encoding. Clearly, this is far from optimal.
How could we read partial Blob/ArrayBuffer responses using XHR? When I try in Chrome, the entire ArrayBuffer/Blob is made available when readyState = 4, but not before that.
To summarize, it seems to me that:
Am I missing something here? What approach could we take to read partial binary responses?
Keep your eyes on the fetch API, currently supported by Firefox and Chrome.
There is a way, though it's not standard yet. Firefox allows you to set responseType
on XHR to "moz-blob", "moz-chunked-text" or "moz-chunked-arraybuffer", depending on which one works for you. Then, when you listen for the progress
event, you will be able to access partial data as it comes in. MDN has more info on that here and here.
Chrome will support the Streams API, but it's not ready yet. Firefox may also eventually support it. I read somewhere that IE does already, though I can't seem to find any official documentation to confirm that.
The best API to use as an XHR replacement is fetch with readableStream.
This is explained here: https://developers.google.com/web/fundamentals/primers/async-functions#example_streaming_a_response
Chrome already supports it. Firefox implements it but it must be activated manually for the moment (it will be activated by default in a future version). While waiting for this activation, Firefox implements the XHR with the non-standard response type moz-chunked-arraybuffer
The library https://www.npmjs.com/package/fetch-readablestream proposes an API that implements these two methods. It uses https://www.npmjs.com/package/web-streams-polyfill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With