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
2 Answers
Reset to default 3Your 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
版权声明:本文标题:How to download a file from URL using JavaScript or jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741452402a2379560.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论