2

我正在尝试发送 PDF 文件。这是正在执行的代码:

$file_path = '/path/to/file/filename.pdf'
$file_name = 'filename.pdf'

header("X-Sendfile: $file_path");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename='$filename'");
readfile($file_path):

每当我直接下载文件时,都很好。但是,当我尝试通过此脚本下载文件时,下载的文件无法打开。我的 pdf 阅读器告诉我它无法打开“text/plain”类型的文件。我也尝试将 设置Content-typeapplication/pdf,但我得到了同样的错误。我在这里做错了什么?

4

2 回答 2

4

你试过这个吗?

$file = '/path/to/file/filename.pdf';
header('Content-Disposition: attachment; filename="'. basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);

使用readfile()还可以消除您可能遇到的任何内存问题。

于 2013-01-23T16:15:51.790 回答
1

试试下面的代码。

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

$file = "filename.pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/force-download");
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)

如果上述方法对您没有帮助,请尝试以下方法

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($file));
ob_clean();
flush();
readfile($file);
exit;

不要$file_path按要求设置文件路径。

于 2013-01-23T16:12:28.340 回答