I am currently working on the HTML5 File API, and I need to get binary file data.
readAsDataURL methods work fine, but
readAsBinaryString returns the same data as
I need binary data, but im getting a text string. Am I missing something?
readAsBinaryString says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between
readAsBinaryString, but with
readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see,
readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and
readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with
responseType = "arraybuffer" is supported in HTML 5.
©2020 All rights reserved.