我用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);
$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);
解决方案 »
- php+ajax里php怎么取ajax传递过来的值
- PHP碰到一个怪问题,做一个排班表的时候,循环显示时间的时候到第五个就多加了一秒!!!!
- 复选框取值问题
- 为什么不能上传图片?
- 小弟遇到一难题 求大神帮忙
- 应届毕业生做PHP程序开发的基本要求是什么?
- php脚本的超时的解决办法???
- 这是什么意思:Unable to jump to row 0 on MySQL result index 3
- 一小公司上机题目,我去,大家看下多久能做完。。。。
- 最近在整合umeditor编辑器遇到了一些问题求那位朋友给我解答一下
- php中 for循环的写法
- 怎么用QQ扫一扫来关注微信公众号,或者用QQ扫一扫跳转到微信,再来关注公众号?
去掉程序文件的最后一个 ?>