Skip to content

Instantly share code, notes, and snippets.

@ozzi-
Last active March 29, 2021 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozzi-/00f21d5e15e95cd548c94414419b4b3e to your computer and use it in GitHub Desktop.
Save ozzi-/00f21d5e15e95cd548c94414419b4b3e to your computer and use it in GitHub Desktop.
JS - Download a binary file via XHR then prompt the save file dialog
<html>
<a id="downloadBinaryLink"></a>
<script>
// file.php here serves as a pseudo API that returns a binary as octect stream (and according Access-Control-Allow-Origin header)
doBinaryDownload("http://oz-web.com/file.php", loadBinaryScriptEdit);
function loadBinaryScriptEdit(blob){
var dataUri = window.URL.createObjectURL(blob);
var anchor = document.getElementById("downloadBinaryLink");
anchor.setAttribute('href', dataUri);
anchor.setAttribute('download', "pingsender.exe");
anchor.click();
}
function doBinaryDownload(url, callback) {
var request = new XMLHttpRequest();
request.responseType = "blob";
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = "";
try {
response = request.response;
} catch (e) {
// do error handling
}
callback.apply(this,[response]);
}
}
};
request.open("GET", url);
request.send();
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment