![](/img/trans.png)
[英]Downloading PHP HTML content as PDF in CodeIgniter not displaying properly
[英]PDF Downloading not functioning properly
我正在使用以下代码下载PDF。...
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="NewName.pdf"');
readfile($root_path.'/full-tile-book.pdf');
它是一个13 MB的文件,只能下载130k,当然无法打开。 如何调试这里的问题? 我的pdf路径正确。
也许您遇到了内存/文件大小错误? 过去使用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;
编辑:如果您使用任何session_code,一个好主意是在开始文件转储过程之前结束会话。 我已经更新了我的示例以反映这一点。
我要添加一些项目。 将文件名分配给$ file,然后尝试:
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
这将确保客户端期望正确的长度,并且输出缓冲区在两者之间很好地刷新。
看到下载的文件在PHP中可能使用了错误的地址。
您可以按照本教程的说明在PHP中下载文件。
必须先发送HTML标头,然后才能将任何输出发送到浏览器。 PHP使用标头函数传递原始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中设置要下载文件的目录。 确保不要在$ dir中使用。 然后,我们检查以确保在请求中指定了文件名。 如果指定了文件,则将$ file设置为文件和文件名的路径。 现在准备工作已经完成,可以将文件发送到浏览器了。
第一个标头语句告诉浏览器进行下载。 接下来的两个标题语句分别告诉浏览器数据的格式和文件的大小。 最后一个标头语句告诉浏览器文件名。 最后,readfile语句将文件发送到浏览器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.