Alex Granados
Alex Granados

Reputation: 146

How to download a file after AJAX call

How can I automatically download a file after an AJAX call? Now my AJAX call is redirecting me to the resource, but not downloading the file.

this is my AJAX call:

$('.download').click(function (e) {
    e.preventDefault();
    let videoId = $('#video').data('video-id');
    $.ajax({
        url: "/video/" + videoId + "/download-link",
        type: "GET",
        success: function (response) {
            window.location = response.link;
        }
    });

});

And this is the html tag:

<a href="#" class="download">
     <i class="fas fa-long-arrow-alt-down"></i>Download
</a>

Upvotes: 0

Views: 3948

Answers (2)

ehab
ehab

Reputation: 8014

what you should do is make sure that the server responds with the following header for the file url

Content-Disposition: attachment; filename="file-name" // file name is not required, and can be ommitted
// This will make browsers understand that this is a downloadable resource

and then in your ajax do this

...
window.open(response.link, '_blank');

Upvotes: 0

Devinder
Devinder

Reputation: 125

because you are redirecting it manually via window.location. There are multiple ways to download file if you have resource link. One of them is to use download attribute .( Also You can always try to search if same question exists already before posting it as new question). You can find detailed answer here : Download File Using Javascript/jQuery

Upvotes: 1

Related Questions