2013-03-05 98 views
-3

使用php头文件和readfile函数下载word文件时出现问题。 在Mozilla Firefox中下载时反应良好,但使用谷歌浏览器和IE时效果不佳。请指导我解决此问题。如何在chrome和IE上使用php下载word文件

这里是我的代码:

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); 
+0

是否检查实际的文件是否存在?为什么不检查'filesize'和'readfile'返回值以确保它们是预期的。 – 2013-03-05 07:44:29

回答

2

试试下面的代码。

<?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(); 
     } 
    } 
} 
?> 
+0

非常棒......这解决了我的docx腐败问题。感谢发布! – 2013-04-19 00:14:06

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); 
?>