Skip to content

Instantly share code, notes, and snippets.

@joaolucasgtr
Last active July 10, 2020 00:42
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 joaolucasgtr/f476cddc4f5383e211fb70dfd13bcc72 to your computer and use it in GitHub Desktop.
Save joaolucasgtr/f476cddc4f5383e211fb70dfd13bcc72 to your computer and use it in GitHub Desktop.
Automatically "download" a pdf you retrieved from api.
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