Skip to content

Instantly share code, notes, and snippets.

@mrofi
Last active August 27, 2021 07:05
Show Gist options
  • Save mrofi/cf1d40aadeeb7c7923bd0fdacc12af83 to your computer and use it in GitHub Desktop.
Save mrofi/cf1d40aadeeb7c7923bd0fdacc12af83 to your computer and use it in GitHub Desktop.
Downloadable Link
// Response Header
Header('Filename: filename.ext');
// html
<a href="path/to/file" download>Link</a>
// js
$('[download]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
var request = new XMLHttpRequest();
var html = $(this).html();
$(this).html('Downloading ...');
$(this).attr('disabled', 'disabled');
request.responseType = "blob";
request.open("GET", url);
var self = this;
request.onreadystatechange = function () {
if (request.readyState === 4) {
var file = request.getResponseHeader('Filename');
var anchor = document.createElement('a');
anchor.download = file;
anchor.href = window.URL.createObjectURL(request.response);
anchor.click();
$(self).html(html);
$(self).removeAttr('disabled');
}
};
request.send();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment