Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial XHR response reading for binary data, possible?

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:

  • Reading XHR's responseText property: Responses can be read before readyState = 4, and we can stream base64 encoded binary data back to the client
  • Reading XHR's response property with responseType = 'arraybuffer': No partial response reading, but the entire buffer is made available when readyState = 4

Am I missing something here? What approach could we take to read partial binary responses?

like image 444
bjornl Avatar asked Sep 23 '13 02:09

bjornl


3 Answers

Keep your eyes on the fetch API, currently supported by Firefox and Chrome.

like image 175
Vladimir Panteleev Avatar answered Sep 17 '22 18:09

Vladimir Panteleev


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.

like image 40
brianchirls Avatar answered Sep 20 '22 18:09

brianchirls


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.

like image 27
Laloi Avatar answered Sep 21 '22 18:09

Laloi