Created
September 13, 2015 07:19
-
-
Save abbotto/1e9f275877cef9408e60 to your computer and use it in GitHub Desktop.
Open a blob in a browser tab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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