How to download file with javascript?

前端 未结 3 779
南笙
南笙 2021-01-12 13:44

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 f

相关标签:
3条回答
  • 2021-01-12 14:41

    since the answer from @saibbyweb does not work in all browsers as I write this, i recommend an other but similar solution, tested and working in latest (as of writing) Firefox, Chrome, Opera, Edge, Safari, mobile Safari, mobile Chrome:

    function downloadUrl(url){
        window.open(url, '_self');
    }
    

    Needless to say you could also open links in new Tabs with _blank instead of _self, but you potentially startle Popup-Blockers by opening new tabs/windows with Javascript.

    0 讨论(0)
  • 2021-01-12 14:46

    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.

    0 讨论(0)
  • 2021-01-12 14:50

    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();
    }
    
    0 讨论(0)
提交回复
热议问题