Created
October 26, 2022 00:26
-
-
Save akosiyawin/9c24c2047d51cdc8c2898e49015c75bd to your computer and use it in GitHub Desktop.
Download a file from same/different origin.
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
//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