Integrate download button with Ajax functionality in your application in 60 seconds.
This article is for people who want to place a working download button in their website for letting users download some remote files.
Step 1: Place the below code in your html code where you want your button to be placed
<button type=”button” id=”GetFile”>Get File!</button>
Change the id with the new id you want.
Step 2: On the same page place the following code inside <script> tags.
<script>
$(‘#GetFile’).on(‘click’, function () {
$.ajax({
url: ‘________________________________________________’,
method: ‘GET’,
xhrFields: {
responseType: ‘blob’
},
success: function (data) {
var a = document.createElement(‘a’);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = ‘_______________’;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
});
</script>
In url give the remote link of the file you want users to download. In a.download= ‘___’ give the name by which you want the file to be downloaded. For example ‘sample.pdf’ or ‘sample.mp3’