我用PHP开发了文档下载功能,但是下载的文件都不能打开报“文件已损坏,无法打开”错误。我将任何word或者excel文件上传到服务器,再用下面代码下载时,会出现文件损坏,无法打开的错误。同意尝试修复后,会打开修复的文件。我将下载后的文件用文本编辑器打开,看到文件结尾被插入0D0A,即回车换行。查上传的文件,没有问题,无论源文件还是服务器上的文件都可以正确打开,文件尾部也没有加上回车换行。经测试,这个回车换行是header插入的,应该是http定义的。问题是,上述代码很经典,网上几乎所有博客都在用,难道没有人有同样的问题,或者是我有没有理解的内容?请大牛指教!主要代码如下:
$file = fopen("$filepath", "rb");     $buffer=1024;
$file_size=filesize("$filepath");
$file_count=0;  //计数器,计算发送了多少数据 
header("Content-type: text/html; charset=utf-8");
header("content-type: application/octet-stream");
header("accept-ranges: bytes");
header("accept-length:".filesize($filepath));
header("content-disposition: attachment; filename="."$filename_utf");
header('Content-Transfer-Encoding: binary');   //输出文件内容     transfer out of content of file.
   //读取文件内容并直接输出到浏览器  read file's content and immediate transfer to browser

          while(!feof($file) or ($file_size>$file_count))
          {
            //如果文件还没读到结尾,且还有数据没有发送  check if it is not end of file and data has not delivered complete yet.
            $senddata=fread($file,$buffer);
            //读取文件内容到缓存区 add file's content to buffer
            $file_count+=$buffer;
            echo $senddata; 
          }
          fclose($file);