How to trigger a file download when clicking an HTML button or JavaScript

前端 未结 21 2561
终归单人心
终归单人心 2020-11-22 05:27

This is crazy but I don\'t know how to do this, and because of how common the words are, it\'s hard to find what I need on search engines. I\'m thinking this should be an ea

相关标签:
21条回答
  • 2020-11-22 06:10

    If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:

    <div onClick=(()=>{downloadjs(url, filename)})/>

    *it's jsx/react syntax, but can be used in pure html

    Note: Edited to fix layout issue above

    0 讨论(0)
  • 2020-11-22 06:11

    If you use the <a> tag, do not forget to use the entire url which leads to the file -- i.e.:

    <a href="http://www.example.com/folder1/file.doc">Download</a>
    
    0 讨论(0)
  • 2020-11-22 06:12

    You can hide the download link and make the button click it.

    <button onclick="document.getElementById('link').click()">Download!</button>
    <a id="link" href="file.doc" download hidden></a>
    
    0 讨论(0)
  • 2020-11-22 06:13

    For me ading button instead of anchor text works really well.

    <a href="file.doc"><button>Download!</button></a>
    

    It might not be ok by most rules, but it looks pretty good.

    0 讨论(0)
  • 2020-11-22 06:18

    You can do it with "trick" with invisible iframe. When you set "src" to it, browser reacts as if you would click a link with the same "href". As opposite to solution with form, it enables you to embed additional logic, for example activating download after timeout, when some conditions are met etc.

    It is also very silient, there's no blinking new window/tab like when using window.open.

    HTML:

    <iframe id="invisible" style="display:none;"></iframe>
    

    Javascript:

    function download() {
        var iframe = document.getElementById('invisible');
        iframe.src = "file.doc";
    }
    
    0 讨论(0)
  • 2020-11-22 06:18

    Anywhere between your <body> and </body> tags, put in a button using the below code:

    <button>
        <a href="file.doc" download>Click to Download!</a>
    </button>
    

    This is sure to work!

    0 讨论(0)
提交回复
热议问题