Integrate download button with Ajax functionality in your application in 60 seconds.

Saiyad Faizan Ali
1 min readFeb 19, 2021

--

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’

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Saiyad Faizan Ali
Saiyad Faizan Ali

Written by Saiyad Faizan Ali

0 Followers

I am a Python Developer. I want to share my experiences so that others get solutions for the generic problems without any haste.

No responses yet

Write a response