我正在使用php下载PDF / DOC文件
这是我的HTML代码:
<a title="Download" target="_new" href="includes/pdf_server.php?file=test.pdf">Test PDF</a>
这是我在pdf_server.php文件中的php代码
<?php
$file = $_GET["file"];
if (file_exists("../PDF/".$file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("../PDF/".$file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
PDF 是我拥有 test.pdf 文件的文件夹。当我点击链接下载文件。浏览器显示要下载的文件大小(1.4 mb),但下载完成后我打开文件显示错误文件已损坏或不支持文件。然后我检查它显示0字节的属性。
请帮忙
答案 0 :(得分:4)
试试这个 -
<?php
$file_name = $_GET["file"];
if (file_exists("../PDF/".$file_name)) {
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ("../PDF/".$file_name)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.'application/pdf');
header('Content-Disposition: attachment; filename="'.basename("../PDF/".$file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file_name)); // provide file size
header('Connection: close');
readfile("../PDF/".$file_name); // push it out
exit();
}
?>