Skip to content

Instantly share code, notes, and snippets.

@OmShiv
Last active December 14, 2015 04:29
Show Gist options
  • Save OmShiv/5028358 to your computer and use it in GitHub Desktop.
Save OmShiv/5028358 to your computer and use it in GitHub Desktop.
Binary data in the OLD Web and the new HTML5 Web, via AJAX
/*
** OLD
*/
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
// Trick to pass bytes through unprocessed.
xhr.overrideMimeType('text/plain; charset=x-user-defined')
xhr.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
var binStr = this.responseText;
for (var i = 0, len = binStr.length; i < len; ++i) {
var c = binStr.charCodeAt(i);
//String.fromCharCode(c & 0xff)
var byte = c & 0xff; // byte at offset i
}
}
};
xhr.send();
/*
** HTML5 - XmlHttpRequest2 (The new Web)
*/
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note: not xhr.responseText
var byte3 = uInt8Array[4]; // byte at offset 4
}
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment