Is it possible to partially read the XHR response for binary data?

I am currently studying the possibility of reading partial binary XHR responses. Our current approach is based on the responseText and base64 property. Clearly, this is far from optimal.

How can we read partial Blob / ArrayBuffer answers using XHR? When I try in Chrome, the entire ArrayBuffer / Blob array becomes available when readyState = 4, but not earlier than that.

To summarize, it seems to me that:

  • Reading the XTR property responseText: responses can be read up to readyState = 4, and we can pass the binary64 encoded binary data back to the client
  • Reading the XHR response property with responseType = 'arraybuffer': there is no partial response, but the entire buffer becomes available when readyState = 4

Am I missing something? What approach can be taken to read partial binary answers?

+6
source share
3 answers

Stay tuned for the fetch API , which is currently supported by Firefox and Chrome .

+3
source

There is a way, although it is not yet standard. Firefox allows you to set responseType on XHR to moz-blob, moz-chunked-text, or moz-chunked-arraybuffer, whichever works for you. Then, when you listen to the progress event, you can access partial data as it arrives. MDN has more details on this here and here .

Chrome will support the Streams API , but not yet ready . Firefox may also end up supporting it. I read somewhere that IE does this, although I cannot find the official documentation to confirm this.

+5
source

The best API to use as an XHR replacement is fetching 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 at the moment (it will be activated by default in a future version). Pending this activation, Firefox will implement XHR with the non-standard response type moz-chunked-arraybuffer

The https://www.npmjs.com/package/fetch-readablestream library offers an API that implements these two methods. It uses https://www.npmjs.com/package/web-streams-polyfill .

+1
source

Source: https://habr.com/ru/post/954375/


All Articles