在jquery中下载pdf文件

时间:2015-03-24 06:19:57

标签: php jquery pdf download

通过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>

的download.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";
}

1 个答案:

答案 0 :(得分:3)

试试这个:

<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。没有跨浏览器方式强制浏览器在JavaScript中显示一个存储对话框,用于通过AJAX从服务器接收的任意数据blob。