admin管理员组

文章数量:1289637

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

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();
Share Improve this question edited Feb 17, 2022 at 12:38 bad_coder 12.9k20 gold badges54 silver badges88 bronze badges asked May 23, 2018 at 11:25 bhaskerbhasker 311 gold badge1 silver badge3 bronze badges 1
  • a.setAttribute("download", "filename"); – RK_oo7 Commented Oct 19, 2019 at 14:28
Add a ment  | 

2 Answers 2

Reset to default 3

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

This code snippet will download from external source

<a onclick="saveFile('url')">Download</a>

<script>
    function saveFile(url) {
    // Get file name from url.
    var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
        a.download = filename; // Set the file name.
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        delete a;
    };
    xhr.open('GET', url);
    xhr.send();
    }
</script>

the saveFile('url') takes string url as an argument so pass in the correct url and your file will download directly. Worked for me

本文标签: How to download a file from URL using JavaScript or jQueryStack Overflow