Skip to content

Instantly share code, notes, and snippets.

@tincho
Created October 25, 2017 16:15
Show Gist options
  • Save tincho/49f19de9b44ae38ea581ceef41de3aa6 to your computer and use it in GitHub Desktop.
Save tincho/49f19de9b44ae38ea581ceef41de3aa6 to your computer and use it in GitHub Desktop.
script for downloading HTTP-Auth'ed file through XHR
var form = document.getElementById("dlFile");
form.onsubmit = function(e) {
e.preventDefault();
var user = form.user.value; // "mayoristas";
var pass = form.pass.value;
requestFile(user, pass);
return false;
}
$('#passwordForm').on('shown.bs.modal', function (e) {
form.pass.focus();
});
function requestFile(user, pass) {
var authStr = window.btoa(user + ':' + pass);
var request = new XMLHttpRequest();
request.open('GET', form.action);
request.setRequestHeader("X-Requested-With", 'XMLHttpRequest');
request.setRequestHeader('Authorization', 'XBasic ' + authStr);
request.responseType = 'blob';
request.onreadystatechange = xhrHandle({
200: function(req) {
$("#passwordForm").modal('hide');
triggerDownload(req);
},
401: function(req) { alert ("no autorizado!") },
404: function(req) { alert("no encontrado!"); }
}, resetForm);
disableForm();
request.send();
function resetForm() {
form.pass.removeAttribute("disabled");
form.pass.value = "";
form.dlbutton.removeAttribute("disabled");
}
function disableForm() {
form.pass.setAttribute("disabled", "disabled");
form.dlbutton.setAttribute("disabled", "disabled");
}
}
function triggerDownload(request) {
var contentType = request.getResponseHeader("Content-Type");
var fileName = request.getResponseHeader("Content-Disposition").match(/filename\=(.*)/)[1];
var blob = request.response;
if (!Blob.prototype.isPrototypeOf(blob)) {
blob = new Blob([request.response], {type: contentType});
}
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
downloadLink(blob, fileName);
}
function downloadLink(blob, fileName) {
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
// dejar opcion de un link visible?
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
}
function xhrHandle(on, _finally) {
return function(e) {
var request = this;
if (! (request.readyState === 4)) return;
(_finally || noop)(request);
return (on[request.status] || noop)(request);
};
function noop() {};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment