Skip to content

Instantly share code, notes, and snippets.

@akosiyawin
Created October 26, 2022 00:26
Show Gist options
  • Save akosiyawin/9c24c2047d51cdc8c2898e49015c75bd to your computer and use it in GitHub Desktop.
Save akosiyawin/9c24c2047d51cdc8c2898e49015c75bd to your computer and use it in GitHub Desktop.
Download a file from same/different origin.
//It is important to add the origin to the AllowedOrigins on your backend. Avoid using wildcard like '*' - chances it will not work.
function forceDownload(url, fileName) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.responseType = "blob";
xhr.onload = function () {
const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(this.response);
const tag = document.createElement("a");
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
};
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment