0

我目前有以下内容:

if (headers_sent()) {

    echo 'HTTP header already sent';
} else {
    if (!is_file($path)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($path)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        ob_start();
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header('Content-Description: File Transfer');
        header("Content-Type: octet-stream");
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header("Content-Length: ".filesize($path));
        header("Content-Disposition: attachment; filename=\"".basename($path)."\"");
        ob_clean();
        ob_flush();
        readfile($path);

        exit;

上面的代码会生成正确文件名的文件下载,但有一点不同。

下载的文件有一些来自下载页面的 html(标题发送不正确?)然后在下载的文档中有乱码文本(例如 OJQJ^J.??. WW8Num2z0)占据了几页。最后,在 .doc 的末尾,我可以阅读一些似乎是 .doc 正确文本的英文,但没有格式。

这些问题在 Chrome 和 Mozilla 中仍然存在。

任何帮助将不胜感激。提前致谢。

编辑:

我开始使用只有一行文本的 .doc 进行测试:“test”

该文件可以从它上传到的目录中手动打开,并验证它没有损坏。但是,使用迄今为止推荐的任何方法下载此文件都会产生几页乱码(实际文件只有 1 行)。文件的实际文本,即“test”,在 66 页乱码中的最后一页中找到,在这个大海捞针中找到:?test ?"ᄚ? ᄚ?!ᄚn"ᄚn#ミn$ミn3P(20???՜.モラ+,??՜.モラ+,???根条目???????? ?F@CompObj????jOle ??????? ?1Table????????????ᆬSummaryInformation(???????WordDocument????????????"$DocumentSummaryInformation8???????????? [t????????????????

4

2 回答 2

1

else最后一个没有任何冲洗功能的摘录试试

header("HTTP/1.1 200 OK");
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=".basename($path));
header("Content-Description: File Transfer"); 
@readfile($path); 
于 2012-11-07T03:59:58.020 回答
1

这些是什么?

    header("Content-Type: octet-stream");
    header("Content-Transfer-Encoding: binary");

将您的代码精简为一个工作示例并从那里扩展它。您不需要设置状态码,PHP 会为您完成。您也不需要设置 Content-length。只发送这个应该可以工作:

$path = 'foo.dat';

if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($path)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($path)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        header("Content-Disposition: attachment; filename=\"".basename($path)."\"");
        readfile($path);
    }
}
于 2012-11-07T09:10:44.643 回答