简体   繁体   English

从onClick方法返回的下载文件

[英]Download file returned from the onClick method

Say I have a function that makes an API call which returns a URL - how can I start a download with that link. 假设我有一个可以进行API调用并返回URL的函数-如何通过该链接开始下载。

So I have the function: 所以我有功能:

function myF() {

  $.ajax{
     //Some GET cal

     return url
  }

}

And then a button: 然后一个按钮:

<button onclick="myF()">some</button>

$.ajax{
//your request
success: function() {
        window.location = '<YOUR_URL>'; //url that you got from response
    }
}

This works if your response url is in the same origin. 如果您的响应网址来自同一来源,则此方法有效。

You can find about more here : download file using an ajax request 您可以在此处找到更多信息: 使用ajax请求下载文件

You can try html5 download attribute, see example: 您可以尝试html5 download属性,请参见示例:

$.ajax({
    // config
}).then((res) => {
    var a = document.createElement('a');
    a.download = 'your file name';
    a.href = res.data.url;
    a.click();
})

If it's a simple URL, I prefer to use an <a> element, and then give it a button appearance in CSS: 如果它是一个简单的URL,我更喜欢使用<a>元素,然后在CSS中为其提供按钮外观:

<a href="download-url" class="btn">Click here to Download</a>

And if it's a URL generated in JavaScript, you can add the url via DOM manipulation: 如果它是用JavaScript生成的URL,则可以通过DOM操作添加该URL:

document.getElementsByClassName("btn")[0].href = "download-url";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM