Created
July 5, 2017 07:54
-
-
Save bartoszbobin/775857708a2d06a4d3b9cff4364f2114 to your computer and use it in GitHub Desktop.
Javascript - pobranie pliku z backendu na front FF, Chrome, Edge, Safari, IE10+
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
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