简体   繁体   中英

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.

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

You can try html5 download attribute, see example:

$.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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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