【问题标题】:Javascript download linkJavascript 下载链接
【发布时间】:2012-06-24 15:43:18
【问题描述】:

有什么方法可以创建一个下载文件的链接,而无需用户右键单击并选择“将链接的文件另存为”?您需要 PHP 来执行此操作还是只能使用 Javascript 执行?

【问题讨论】:

标签: javascript hyperlink download save


【解决方案1】:

标识文件下载的 HTTP 响应标头由服务器发送,因此无法使用 JavaScript 发送。您可能需要一些服务器端代码行来设置正确的标头(例如 PHP 的 header() 函数)。

【讨论】:

    【解决方案2】:

    这里有一些例子,你可以用 JavaScript 来做,但它只适用于 IE

    <html>
    <head>
    <title>xbs_saveas_gt</title>
    <script type="text/javascript">
    function go_saveas() {
        if (!!window.ActiveXObject) {
            document.execCommand("SaveAs");
        } else if (!!window.netscape) {
            var r=document.createRange();
            r.setStartBefore(document.getElementsByTagName("head")[0]);
            var oscript=r.createContextualFragment('<script id="scriptid" type="application/x-javascript" src="chrome://global/content/contentAreaUtils.js"><\/script>');
            document.body.appendChild(oscript);
            r=null;
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                saveDocument(document);
            } catch (e) {
                //no further notice as user explicitly denied the privilege
            } finally {
                var oscript=document.getElementById("scriptid");    //re-defined
                oscript.parentNode.removeChild(oscript);
            }
        }
    }
    </script>
    </head>
    <body>
    <a href="#" onclick="go_saveas();return false">save the document</a><br />
    </body>
    </html> 
    

    或者您也可以直接使用document.print() 并将其保存为 PDF 文件

    【讨论】:

      【解决方案3】:

      你可以用 php 和 header-function 解决这个问题,像这样:

      <?php
      $fileToOpen = "document.txt"; // the file that you want to download
      header("Content-disposition: attachment; filename=$fileToOpen");
      header("text/plain"); // Depending on the file
      echo file_get_contents($fileToOpen);
      

      因此您的链接将指向 php 文件而不是直接指向文档...

      【讨论】:

        【解决方案4】:

        简单的PHP:

        <?php
            header("Content-type: application/octet-stream");
            header("Location:filenamegoeshere.txt");
            header("Pragma: no-cache");
            header("Expires: 0");
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-03
          • 2019-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多