how to download a file from url using javascript or jquery?

bhasker picture bhasker · May 23, 2018 · Viewed 23.2k times · Source

I used jquery fileDownload plugin to download a file from URL. But it's not working. It is always failing please help with this

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

Even I tried with javascript 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();

Answer

Krzysztof Janiszewski picture Krzysztof Janiszewski · May 23, 2018

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();