How to download a file from URL using JavaScript or jQuery?

26,782

Your JavaScript does not work probably because you append a to body before you add href and download attributes.

Append just before triggering click

Also remember that this will only work on files with the same-origin URLs (Source).

This attribute only works for same-origin URLs.

var a = document.createElement("a");
a.href = url;
fileName = url.split("/").pop();
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();
Share:
26,782
bhasker
Author by

bhasker

Updated on February 18, 2022

Comments

  • bhasker
    bhasker about 2 years

    I used jQuery fileDownload plugin to download a file from URL.

    $.fileDownload(url,{
        contentType: "text/csv",
        contentDisposition: 'attachment; filename=' + 
            url.split("/").pop()
    })
    .done(function(){console.log('successfully downladed')})
    .fail(function(){ console.log(`request failed`)});
    

    I even tried with JavaScript but it's not working

    var a = document.createElement("a");
    document.body.appendChild(a);
    a.href = url;
    fileName = url.split("/").pop();
    a.download = fileName
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();