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

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

    Another way of doing in case you have a complex URL such as file.doc?foo=bar&jon=doe is to add hidden field inside the form

    <form method="get" action="file.doc">
      <input type="hidden" name="foo" value="bar" />
      <input type="hidden" name="john" value="doe" />
      <button type="submit">Download Now</button>
    </form>
    

    inspired on @Cfreak answer which is not complete

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

    What about:

    <input type="button" value="Download Now!" onclick="window.location = 'file.doc';">
    
    0 讨论(0)
  • 2020-11-22 06:08

    I think this is the solution you were looking for

    <button type="submit" onclick="window.location.href='file.doc'">Download!</button>
    

    I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.

    downloadCSV: function(data){
        var MIME_TYPE = "text/csv";
    
        var blob = new Blob([data], {type: MIME_TYPE});
        window.location.href = window.URL.createObjectURL(blob);
    }
    
    0 讨论(0)
  • 2020-11-22 06:08

    download attribute do it

     <a class="btn btn-success btn-sm" href="/file_path/file.type" download>
         <span>download </span>&nbsp;<i class="fa fa-download"></i>
     </a>
    
    0 讨论(0)
  • 2020-11-22 06:09

    HTML:

    <button type="submit" onclick="window.open('file.doc')">Download!</button>
    
    0 讨论(0)
  • 2020-11-22 06:09

    Bootstrap Version

    <a class="btn btn-danger" role="button" href="path_to_file"
       download="proposed_file_name">
      Download
    </a>
    

    Documented in Bootstrap 4 docs, and works in Bootstrap 3 as well.

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