Skip to content

Instantly share code, notes, and snippets.

@bartoszbobin
Last active July 5, 2017 08:26
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 bartoszbobin/22cd8264cda932d3d96e043fca44f421 to your computer and use it in GitHub Desktop.
Save bartoszbobin/22cd8264cda932d3d96e043fca44f421 to your computer and use it in GitHub Desktop.
Javascript - pobranie pliku z backendu na front FF i przekazanie do pobrania, Chrome, Edge, Safari, IE10+
var xhr = new XMLHttpRequest();
xhr.open('POST', 'nasz-url', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// należy wymusić 'arraybuffer'
xhr.responseType = 'arraybuffer';
xhr.onload = onLoad;
xhr.send();
function onLoad() {
if (this.status !== 200) {
return;
}
// sciagamy nazwe pliku z nagłówków
var filename = getFilenameFromHeaders(filename);
// typ pliku
var fileContentType = xhr.getResponseHeader('Content-Type');
var blob = new Blob([this.response], {type: fileContentType});
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// Obejscie na IE # HTML7007: One or more blob URLs were revoked by closing the blob for which
// they were created. These URLs will no longer resolve as the data backing the URL has been freed.
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// bedziemy używać a[download]
var a = document.createElement("a");
// sprawdzenie czy przeglądarka wspiera attrybut [download]
if (typeof a.download === 'undefined') {
window.location.open = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
// dodajemy niewidoczny element do body i go klikamy
document.body.appendChild(a);
a.click();
}
} else {
window.location.open = downloadUrl;
}
setTimeout(function () {
URL.revokeObjectURL(downloadUrl);
}, 100); // cleanup
}
}
function getFilenameFromHeaders() {
var disposition = xhr.getResponseHeader('Content-Disposition');
if (!disposition || disposition.indexOf('attachment') === -1) {
return "";
}
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches !== null && matches[1]) {
return matches[1].replace(/['"]/g, '');
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment