【问题标题】:Downloading a pdf file in jquery在 jquery 中下载 pdf 文件
【发布时间】:2015-05-27 09:12:42
【问题描述】:

通过 jquery 中的post 方法,我尝试下载 pdf,但它不起作用。文件没有被下载。我哪里做错了?

main.php

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
        </head>
<body>
    <script>
        function downloadpdf(){
            alert("working");
        $.post('download.php',{pdf:'Intro.pdf'},function(data){if(data=="y"){alert("Downloaded");}});
    }
        </script>
    <button onclick="downloadpdf();">download</button>   
</body>
</html>

下载.php

<?php
    if(isset($_POST['pdf'])){
    $bbpdf=$_POST['pdf'];
header("Content-disposition: attachment; filename=$bbpdf");
header("Content-type: application/pdf");
header('Content-Length: ' . filesize($bbpdf));
readfile($bbpdf);
echo "y";
}

【问题讨论】:

  • 会发生什么,您预计会发生什么? “不起作用”是一个相当薄弱的问题描述..:P
  • 文件没有被下载。我想下载一个pdf文件。
  • 有什么错误吗? js控制台说什么?我可以立即看到的一件事是echo "y"; 将在文件末尾添加y,我猜这不是故意的。您只想打印文件中的数据。
  • 没有错误。实际上,我在 download.php if(isset($_POST['pdf'])){echo "y";} 中尝试过,效果很好。所以,header 下载 pdf 的问题

标签: php jquery pdf download


【解决方案1】:

试试这个:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
    </head>
    <body>
        <a href="download.php?pdf=Intro.pdf">download</a>
    </body>
</html>

<?php
if(isset($_GET['pdf'])){
    $bbpdf = $_GET['pdf'];

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false); // required for certain browsers
    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=\"" . basename($bbpdf));
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($bbpdf));
    ob_clean();
    flush();
    readfile($bbpdf);
}

注意:不要使用 AJAX。对于通过 AJAX 从服务器接收到的任意数据块,没有跨浏览器的方法可以强制浏览器在 JavaScript 中显示另存为对话框。

【讨论】:

  • 它工作正常。那么,有没有办法使用我发布的方法下载文件?
  • 您可以使用 iframe。检查这个链接,如果它可以帮助你 - stackoverflow.com/questions/3613526/…
  • 我有这个问题。加载图标一直显示。文件正在下载,但加载图标并未隐藏,尽管页面已完全加载。$(window).on('beforeunload', function(event) { $('#loading').show(); }); $(window).on('load', function(event) { $('#loading').hide();});
  • beforeunload 触发,但页面未卸载
猜你喜欢
  • 2011-11-26
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
相关资源
最近更新 更多