Last active
August 27, 2021 07:05
-
-
Save mrofi/cf1d40aadeeb7c7923bd0fdacc12af83 to your computer and use it in GitHub Desktop.
Downloadable Link
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
// 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