【问题标题】:PHP - Headers to download pdf filePHP - 下载 pdf 文件的标题
【发布时间】:2018-02-07 17:22:03
【问题描述】:

我使用这行代码在不同的浏览器中下载 pdf 文件。当我在桌面和安卓浏览器上尝试时,没问题,但是当我尝试 Ipad 和 iphone 设备时,下载不会发生。我不知道这段代码是否有错误..

$local_file = $path;
            $download_file = $path;

            // set the download rate limit (=> 20,5 kb/s)
            $download_rate = 100;
            if(file_exists($local_file) && is_file($local_file))
            {
                /*header("Cache-Control: no-cache, must-revalidate"); 
                header('Content-Type: application/pdf');
                header('Content-Length: '.filesize($local_file));
                header('Content-Disposition: filename='.$download_file);

                flush();
                readfile($local_file);*/


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

                $file = $local_file;
                header("Content-Disposition: attachment; filename=" . urlencode($file_name));   
                header("Content-Type: application/octet-stream");
                header("Content-Type: application/download");
                header("Content-Description: File Transfer");            
                header("Content-Length: " . filesize($file));
                flush(); // this doesn't really matter.
                $fp = fopen($file, "r");
                while (!feof($fp))
                {
                    echo fread($fp, 65536);
                    flush(); // this is essential for large downloads
                } 
                fclose($fp); 


            }else {
                die('Error: The file '.$local_file.' does not exist!');
            }

【问题讨论】:

  • 这段代码乱七八糟。

标签: php pdf


【解决方案1】:

首先,下载文件的建议名称应该用双引号括起来,并设置正确的内容类型(需要在客户端上打开正确的查看器):

header("Content-Type: application/pdf; name=\"{$filename}\"");
header("Content-Transfer-Encoding: binary");

然后,不要费心在循环中读取文件,使用: 读取文件($文件); 死();

顺便说一句,在我所有的下载中,我还附加了以下标题(根据你的意图,你可以省略其中的一些):

// to force the client to save the file, not opening it inside the browser
header("Content-Disposition: attachment; filename=\"{$filename}\"");

// disable caching on client and proxies, if the download content vary
header("Expires: 0");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

我建议你清除代码中的标题部分,只使用上面的前两个(暂时不要使用 content-length)。

【讨论】:

    猜你喜欢
    • 2013-12-03
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多