问题
I'm playing with the code snippet from this original question: Read bytes from a binary file with JavaScript, without jQuery
However, for some reasons, a whole different set of bytes appear to be loaded! I suspect this has to do with the string conversion.
Here's a copy of the binary file I am trying to download: http://steeman.dk/html5/coco/colorbasic13.rom
To my local IIS 7.5 server I have added the .rom MIME type as 'application/octet-stream' (I have also tried with 'text/plain; charset=x-user-defined' with the same results).
What I'm expecting is a sequence of bytes starting with this:
a1 cb a2 82 a7 7c a7 0b a7 f4 a9 de a7 d8 10 ce (etc.)
However, what I'm getting is the following:
fd e2 fd fd 7c fd 0b fd fd fd a7 fd 10 fd 03 c6 37 fd fd 23 (etc.)
I am not really seeing a clear pattern apart from a lot of 'fd' being intersparsed. What gives?
BTW is there an easier way of doing this using JQuery?
回答1:
Looks like there is a new way, by using Uint8Array and setting the response type to "arraybuffer":
function loadRom(file, callback)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', file, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e)
{
if (this.status == 200)
{
var bytes = new Uint8Array(this.response);
callback(bytes);
}
}
xhr.send();
}
This works for me!
来源:https://stackoverflow.com/questions/22576518/javascript-read-raw-bytes-from-xmlhttprequest-messed-up