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

前端 未结 21 2560
终归单人心
终归单人心 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:29

    For the button you can do

    <form method="get" action="file.doc">
       <button type="submit">Download!</button>
    </form>
    
    0 讨论(0)
  • 2020-11-22 06:29

    You can trigger a download with the HTML5 download attribute.

    <a href="path_to_file" download="proposed_file_name">Download</a>
    

    Where:

    • path_to_file is a path that resolves to an URL on the same origin. That means the page and the file must share the same domain, subdomain, protocol (HTTP vs. HTTPS), and port (if specified). Exceptions are blob: and data: (which always work), and file: (which never works).
    • proposed_file_name is the filename to save to. If it is blank, the browser defaults to the file's name.

    Documentation: MDN, HTML Standard on downloading, HTML Standard on download, CanIUse

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

    This is what finally worked for me since the file to be downloaded was determined when the page is loaded.

    JS to update the form's action attribute:

    function setFormAction() {
        document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
    }
    

    Calling JS to update the form's action attribute:

    <body onLoad="setFormAction();">
    

    Form tag with the submit button:

    <form method="get" id="myDownloadButtonForm" action="">
        Click to open document:  
        <button type="submit">Open Document</button>
    </form>
    

    The following did NOT work:

    <form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">
    
    0 讨论(0)
提交回复
热议问题