【发布时间】:2011-12-15 16:17:16
【问题描述】:
我有一段代码允许用户从服务器下载文件(文档,如 docs、docx、pdf 等)。
用户可以下载文件,但会出现文件损坏等错误。例如,一个 MS Word 文件下载后需要恢复才能读取内容。
不知这段代码是否有错误(或上传时出现问题?)。
$size_of_file = filesize($download_path);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file_name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size_of_file);
//read file from physical path
readfile($download_path);
【问题讨论】:
-
您可以尝试根据文件类型生成内容类型,而不是始终使用“八位字节流”。另一条评论:尝试删除“文件传输”标题。我在几个项目中做了你想要的,我从来没有使用过这样的标题。
-
您的 readfile() 方法是否打印文件的内容?您应该使用 echo() 命令编写它们。
-
@belgther - readfile() 总是将文件内容打印到标准输出。回到问题,也许你在 readfile 之前打印一些东西(空格,换行符等)并且它会破坏下载的文件?这是可能的,因为恢复后文件正常。
-
@piotrekkr 我找到了问题的根源,我在 php 关闭标记后多了一些空格。