Skip to content

Instantly share code, notes, and snippets.

@abbotto
Created September 13, 2015 07:19
Show Gist options
  • Save abbotto/1e9f275877cef9408e60 to your computer and use it in GitHub Desktop.
Save abbotto/1e9f275877cef9408e60 to your computer and use it in GitHub Desktop.
Open a blob in a browser tab
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
// Return the blob and set the contentType
// Note: .response instead of .responseText
var _viewBlob = function(data, contentType) {
var file = new Blob([data], {
type: contentType
});
// IE won't allow opening a Blob with window.open()
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL, '_blank');
}
};
_viewBlob(this.response, contentType);
} else {
alert('Notice', 'Sorry, there was a problem retrieving the blob. Please try again later.')
}
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment