-4

使用 php header 和 readfile 函数下载 word 文件时出现问题。在 Mozilla Firefox 中下载时响应良好,但在使用 google chrome 和 IE 时效果不佳。请指导我解决此问题。

这是我的代码:

switch(strtolower($ext))
    {
        case "doc": $ctype="application/msword"; break; 
        case "docx": $ctype="application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;                       
        default: $ctype="application/octet-stream"; 
    }

    header('Content-Description: File Transfer');
    //header("Content-type: application/octet-stream");
    header("Content-Type: ".$ctype." "); 
    header('Content-Disposition: attachment; filename='.basename($rw['FINALDOCNAME']));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Pragma: private');
    header('Content-Length: ' . filesize($rw['FINALDOCNAME']));
    ob_clean();
    flush();
    readfile($filepath);
4

2 回答 2

2

Try below code.

<?php
$fdl = @fopen($filePath,'rb');
header("Status: 200");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header("Pragma: hack");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Description: File Transfer");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".$filename."\""); 
header("Content-Transfer-Encoding: binary");
header("Content-Length:".filesize($filePath));  
if($fdl)
{
    while(!feof($fdl)) {
        print(fread($fdl, filesize($filePath)));
        flush();
        if (connection_status()!=0) 
        {
            @fclose($fdl);
            die();
        }
    }
}
?>
于 2013-03-05T07:43:25.010 回答
0
<?php
$todayDate = date('d-m-Y');
$filename = 'untitled.docx';
header('content-type: application/octet-stream');
header('content-Disposition: attachment; filename='.$filename.'-'.$todayDate.'.xls');
header('Pragma: no-cache');
header('Expires: 0');
echo file_get_contents($filename);
?>
于 2013-03-05T07:48:21.593 回答