简体   繁体   English

在jquery中下载pdf文件

[英]Downloading a pdf file in jquery

Through post method in jquery I tried to download a pdf but it doesn't work. 通过jquery中的post方法我试着下载一个pdf,但它不起作用。 File is not getting downloaded. 文件未下载。 where am I doing wrong? 我哪里做错了?

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

Try this: 尝试这个:

<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);
}

Note: Don't use AJAX. 注意:不要使用AJAX。 There is no cross-browser way to force the browser to show a save-as dialog in JavaScript for some arbitrary blob of data received from the server via AJAX. 没有跨浏览器方式强制浏览器在JavaScript中显示一个存储对话框,用于通过AJAX从服务器接收的任意blob数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM