PDF下载无法正常运行

时间:2009-12-23 20:09:33

标签: php download

我使用以下代码下载PDF ....

   header('Content-Type: application/pdf');
   header('Content-Disposition: attachment; filename="NewName.pdf"');
   readfile($root_path.'/full-tile-book.pdf');

这是一个13 MB的文件,只下载像130k,当然无法打开。如何调试问题所在?我的pdf路径是正确的。

3 个答案:

答案 0 :(得分:1)

也许你遇到了内存/文件大小错误?我在过去使用readfile转储大文件时遇到了问题。除了设置Content-Length标头之外,我建议使用fpassthru(),因为它不会将文件读入缓冲区,只是转储它。

set_time_limit(0); // disable timeout
$file = $root_path.'/full-tile-book.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="NewName.pdf"');
header('Content-Length: ' . filesize($file));
session_write_close(); // remove this line if sessions are not active
$f = fopen($file, 'rb');
fpassthru($f);
fclose($f);
exit;

编辑:如果您正在使用任何sessions_code,最好在启动文件转储过程之前结束会话。我已经更新了我的例子以反映这一点。

答案 1 :(得分:0)

我会添加一些项目。将文件名分配给$ file,然后尝试:

header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

这将确保客户端期望正确的长度,并且输出缓冲区在两者之间很好地刷新。

答案 2 :(得分:0)

查看下载的文件可能在PHP中使用了错误的地址 您可以按照本教程在PHP中下载文件。

  

HTML标头必须先发送   输出发送到浏览器。 PHP   使用header函数传递raw   HTML标头。对于这个例子,我们是   从URL获取文件名   www.yourdomain.com/download.php?file=download.zip。

<? 
$dir="/path/to/file/";
if (isset($_REQUEST["file"])) {
    $file=$dir.$_REQUEST["file"];
    header("Content-type: application/force-download");
    header("Content-Transfer-Encoding: Binary");
    header("Content-length: ".filesize($file));
    header("Content-disposition: attachment; filename="".basename($file).""");
    readfile("$file");
} else {
    echo "No file selected";
}
 ?>
  

我们开始设置目录   要下载的文件是哪里   位于$ dir。一定不要使用   $目录。然后我们检查以确保一个   filename已在请求中指定。   如果指定了文件,那么我们设置   $ file到文件的路径和   文件名。现在准备工作了   完成了将文件发送到的时间   浏览器。

     

第一个标题语句告诉了   浏览器期待下载。下一个   两个头语句告诉浏览器   数据的格式和大小   该文件分别。最后一个标题   语句告诉浏览器名称   的文件。最后是readfile   语句将文件发送给   浏览器。

More information.

相关问题