Skip to content

Instantly share code, notes, and snippets.

@000panther
Last active August 29, 2015 14:23
Show Gist options
  • Save 000panther/1d24bb3c262e189395ef to your computer and use it in GitHub Desktop.
Save 000panther/1d24bb3c262e189395ef to your computer and use it in GitHub Desktop.
A binary file download script that also works on android 4.1 - 4.3 devices (without XMLHttpRequest blob support)
function getImageFile(path, callback) {
path = path.replace('https://', 'http://'); // android is very picky with https certificates and does not give an error
console.info("Requesting Image File for Splashscreen: " + path);
if(path == null) {
// handle empty urls by passing on the null value
callback(null);
return deferred.promise;
}
try {
var xhr = new XMLHttpRequest();
try {
xhr.responseType = 'blob';
} catch (e) {
console.info('Feature detection failed');
}
console.info("xhr responsetype" + xhr.responseType);
if (xhr.responseType == 'blob') {
xhr.addEventListener("load", function (e) {
var blob = new Blob([xhr.response], {type: 'image/png'});
callback(blob);
console.log('xhr returned');
});
} else {
// using fallback mode described in various internet forums
console.info('before override mime type');
// to avoid getting the response mangled by the xhr request
xhr.overrideMimeType('text\/plain; charset=x-user-defined');
console.info('after override mime type');
xhr.addEventListener("load", function (e) {
console.info('before checking length');
console.info('before converting blob' + xhr.response.length);
// this is necessary else some overlong bytes are getting mangled
var l, d, array;
d = xhr.response;
l = d.length;
array = new Uint8Array(l);
console.info("Got Uint8Array");
for (var i = 0; i < l; i++) {
array[i] = d.charCodeAt(i) & 0xff;
}
// now we finally can create a blob
var blob = new Blob([array.buffer], {type: 'image/png', 'endings': "transparent"});
console.info('got blob');
callback(blob);
});
}
xhr.addEventListener("error", function (e) {
console.info('xhr error' + JSON.stringify(e));
callback(e)
});
xhr.open('GET', path, true);
xhr.send(null);
} catch (e) {
console.log('Exception' + e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment