Search code examples
javascriptchttpfilereaderarraybuffer

JS ArrayBuffer from XMLHttpRequest text


I've been trying to use an XMLHttpRequest to get a binary file created from a C struct.

If I open the file in a hex editor, all characters are encoded as expected.

If I add the file to a static HTML page using <input type='file' /> and then use FileReader.readAsArrayBuffer(), I can see that the ArrayBuffer holds the same expected values.

But, when I try to send it over an XMLHttpRequest, and put its responseText into an ArrayBuffer, there are several characters that are replaced with the Unicode "replacement character".

If I use FileReader.readAsText() with the <input type='file' /> test, I get the same character dropout that happens with XMLHttpRequest.responseText.

I have control over the file server, and I've tried adding a Content-Type header to the response (application/octet-stream?), but it doesn't seem to make a difference.

What am I missing here to ensure that the XMLHttpRequest.responseText has the correct data so the ArrayBuffer is created with the same values as the FileReader way?


Solution

  • Of course, after hours of working on this, right after I rubber duck on SO I find the solution.

    XMLHttpRequest has a response property - I shouldn't be using responseText. Also, I can set the responseType property before I send the request to ensure it's returned in an ArrayBuffer.