skip to Main Content

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>

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search