【问题标题】:Prompt user to download PDF file instead of opening提示用户下载 PDF 文件而不是打开
【发布时间】:2010-12-20 17:44:42
【问题描述】:

在我的项目站点中,如果我单击链接,PDF 将在新窗口或父窗口中打开。好吧,我希望出现一个框,提示用户下载文件而不是打开它。

有谁知道一个简单的 JavaScript onClick 事件可以在所有浏览器中使用默认设置执行此操作?

我的服务器是基于 PHP 的。

【问题讨论】:

    标签: php javascript apache


    【解决方案1】:

    由于您的编辑表明您正在使用 PHP,以下是如何在 PHP 中执行相同操作:

    <?php
    header('Content-type: application/pdf');
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    readfile('original.pdf');
    ?>
    

    【讨论】:

    • 我想为网站上的所有 pdf 启用此功能,而不是为任何特定的 pdf 启用此功能
    • 包含文件的大小也很有帮助,否则浏览器可能会对剩余的下载大小/时间说“未知”。 header('Content-Length: 12345');
    【解决方案2】:

    既然您已将其标记为 .NET,我会说这是您最好的解决方案:

    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment;filename=download.pdf");
    Response.WriteFile(Server.MapPath("~/files/myFile.pdf"));
    Response.Flush();
    Response.Close();
    

    【讨论】:

      【解决方案3】:

      将 Content-Type 更改为 application/octet-stream。但是,您可能会发现,某些浏览器会根据文件扩展名推断它应该使用您喜欢的 PDF 查看器以 PDF 格式打开。

      Response.ContentType = "application/octet-stream";
      

      另外,设置以下内容:

      Response.AppendHeader( "content-disposition", "attachment; filename=" + name );
      

      【讨论】:

        【解决方案4】:

        你不能通过 javascript 来做,你需要服务器端实现。

        这是应该有帮助的 SO 帖子:
        Allowing user to download from my site through Response.WriteFile()

        【讨论】:

          【解决方案5】:

          【讨论】:

          • 文章所需代码:Response.AppendHeader( "content-disposition", "attachment; filename=" + name );
          【解决方案6】:

          如果您遇到文件损坏错误,请尝试以下操作:

          header('Pragma: public');
          header('Expires: 0');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Cache-Control: private', false);
          header('Content-Type: application/pdf');
          header('Content-disposition: attachment; filename=' . basename($file));
          header("Content-Transfer-Encoding:  binary");
          header('Content-Length: ' . filesize($file)); // provide file size
          header('Connection: close');
          readfile($file);
          

          其中$file 是文件的完整路径或网址

          【讨论】:

            猜你喜欢
            • 2019-12-08
            • 1970-01-01
            • 2016-09-11
            • 2013-10-15
            • 2011-11-18
            • 1970-01-01
            • 1970-01-01
            • 2018-11-10
            • 1970-01-01
            相关资源
            最近更新 更多