Last active
July 10, 2020 00:42
-
-
Save joaolucasgtr/f476cddc4f5383e211fb70dfd13bcc72 to your computer and use it in GitHub Desktop.
Automatically "download" a pdf you retrieved from api.
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
let url = 'https://<your pdf endpoint>'; | |
let filename = 'File.pdf'; | |
let xhr = new XMLHttpRequest(); | |
xhr.responseType = 'blob'; // set response type to blob | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState == 4 && xhr.status == 200) { | |
// create a blob with the content in XHR's response: | |
let blob = new Blob([xhr.response], { type: 'application/pdf' }); | |
// create an invisible HTML anchor tag: | |
let downloadLink = document.createElement('a'); | |
document.body.appendChild(downloadLink); | |
downloadLink.style.display = 'none'; | |
// create URL to your local blob: | |
let url = window.URL.createObjectURL(blob); | |
downloadLink.href = url; | |
// set the file name to download: | |
downloadLink.setAttribute('download', filename); | |
// anonimously click the invisible link you created: | |
downloadLink.click(); | |
// clean out the HTML as soon as the download starts: | |
document.body.removeChild(downloadLink); | |
window.URL.revokeObjectURL(url); | |
} | |
} | |
xhr.open("POST", url); | |
xhr.setRequestHeader("cache-control", "no-cache"); | |
xhr.send(data); | |
/* This is based on that great article from Alex Hadik I found here: https://www.alexhadik.com/writing/xhr-file-download/ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment