Skip to content

Instantly share code, notes, and snippets.

@micalm
Last active October 3, 2018 07:29
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 micalm/da608b8a0bae6e2b6cda to your computer and use it in GitHub Desktop.
Save micalm/da608b8a0bae6e2b6cda to your computer and use it in GitHub Desktop.
XHR Download file
$("#saveAndDownload").click(function() {
var invoiceData = getJsonData();
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'SOME_URL', true);
xhr.responseType = 'arraybuffer';
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
xhr.send(JSON.stringify(invoiceData));
xhr.onload = function(e) {
var arr = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null,arr);
var b64 = btoa(raw);
var filename = this.getResponseHeader('Content-Disposition').split('attachment; filename=')[1]
var element = document.createElement('a');
element.setAttribute('href', 'data:application/pdf;base64,' + b64);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment