我无法强制下载pdf文件

时间:2020-01-10 12:13:12

标签: javascript php kohana

我已经尝试搜索解决我的问题的方法大约2天了,但是我似乎无法使我的代码正常工作。我的目标是单击按钮后下载PDF文件,但我希望为用户隐藏文件的路径。我正在研究的项目正在使用Kohana(3.3)框架。我试图用ajax调用该函数:

public function action_download_pdf()
{
        $this->auto_render = false;
        if ($this->request->post()) {

            $data = $this->request->post();
            $file = 'uploads/pdfs_folder/'.$data['pdf_number'].'.pdf';

            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename='.$data['pdf_number'].'.pdf');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                ob_clean();
                flush();
                readfile($file);
                exit;
            }
        }
    }

我得到状态码:200,但是我只能在开发者控制台的“预览”标签中显示它。

https://i.stack.imgur.com/vyAiK.jpg

我不知道应该怎么做才能下载它,而不是那样显示?

3 个答案:

答案 0 :(得分:0)

这非常适合我。

if ($filename) {

    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=".basename($filename)); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile("$filename");

}

答案 1 :(得分:0)

下面的代码对我来说很好


<?php
    if(isset($_REQUEST['path']) && $_REQUEST['path'] != "") {

        $file_url = $_REQUEST['path'];
        $pdfname = basename ($file_url);
        header('Content-Type: application/pdf');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=".$pdfname);
        readfile($file_url);
    }
?>

在您的代码中,我注意到了

header('Content-Type: application/octet-stream');

PHP中的内容类型参考很重要, 这是您要保护的文件的MIME类型。 例如,如果您保存的是MP3文件,则需要用音频/ mpeg替换application / pdf。

希望这会对您有所帮助。

谢谢

答案 2 :(得分:0)

这就是我解决问题的方式:

我在数据库中创建了一个表,其中生成并保存了一个假数字和一个实数字。 当我点击下载PDF的按钮时,我通过该按钮提交了一个表单,该表单触发了Controller中的功能。该功能是我最初发布的代码。我检查表中的假号码并得到真实的号码。