Last active
March 29, 2021 13:11
-
-
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
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
<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