如何使用javascript下载文件? [英] How to download file with javascript?

查看:105
本文介绍了如何使用javascript下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在按下按钮时下载给定的文件。该文件将通过 API 调用提供。现在,我将其保存在我的文件中本地存储。
所以我的文件夹类似于:

  rootFolder 
-JS文件
-HTML文件
-下载文件(`sample.csv`)

如何创建下载链接?到目前为止,我尝试过的
是:
< a download = sample.csv>< / a>
我还尝试使用 onclick 事件:

 < a download =  sample.csv onclick = download()>< / a> 

函数download |(){
.....调用api`
}


我不知道这2种方式如何:下载 API(如果有一个)和单击事件处理程序,如果您打算在下载时执行其他逻辑。

解决方案

您可以提供链接到此函数以下载文件:

 函数downloadURI(uri,name)
{
var链接= document.createElement( a);
link.download =名称;
link.href = uri;
link.click();
}


I want to be able to download a given file when pressing a button.The file will be provided via an API call.For now, I will have it in my local storage. So my folder is something like :

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 onclick event:

<a download="sample.csv" onclick="download()"></a>

function download|(){
   .....code that calls the `api`
}

I do not know how these 2 fit: the download API if there is one and the click event handler if you plan to do additional logic when downloading.

解决方案

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

这篇关于如何使用javascript下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆