javascript 如何使用javascript下载文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54626186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download file with javascript?
提问by Bercovici Adrian
I want to be able to download a given file when pressing a button.The file will be provided via an APIcall.For now, I will have it in my local storage.
So my folder is something like :
我希望能够在按下按钮时下载给定的文件。该文件将通过API调用提供。现在,我会将其保存在本地存储中。所以我的文件夹是这样的:
rootFolder
-JS file
-HTML file
-download file (`sample.csv`)
How can I create a download link?
I have tried so far with :
<a download="sample.csv"></a>I have also tried using an onclickevent:
如何创建下载link?到目前为止我已经尝试过:
<a download="sample.csv"></a>我也尝试过使用一个onclick事件:
<a download="sample.csv" onclick="download()"></a>
function download|(){
.....code that calls the `api`
}
I do not know how these 2 fit: the downloadAPI if there is one and the clickevent handler if you plan to do additional logic when downloading.
我不知道这两个如何适合:the downloadAPI(如果有)和click事件处理程序(如果您计划在下载时执行其他逻辑)。
回答by saibbyweb
You can provide the link to this function to download the file :
您可以提供此功能的链接以下载文件:
function downloadURI(uri, name)
{
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
回答by Airat Zhanshuakov
You can do it via HTML <a href="/path/to/sample.csv"></a>, but if you have to do it in JS there is https://github.com/eligrey/FileSaver.js/library.
您可以通过 HTML 完成<a href="/path/to/sample.csv"></a>,但如果您必须在 JS 中完成,则可以使用https://github.com/eligrey/FileSaver.js/库。

