尽管我在这里找到了答案:通过Php提供.docx文件但当我试图通过php下载并打开docx服务器时,我仍然收到文件损坏的错误也许你可以看到我的代码有问题。.doc运行良好,是docx失败了。
$parts = pathinfo($doc);
$docFile = $userDocRoot.$doc;
if ( !file_exists($docFile) ){
throw new Exception("Can not find ".$parts ['basename']." on server");
}
if ( $parts['extension'] == 'docx' ){
header('Content-type: application/vnd.openxmlformats- officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="'.$parts['basename'].'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile($docFile);
}else{
header('Content-type: application/msword');
header('Content-Disposition: attachment; filename="'.$parts['basename'].'"');
readfile($docFile);
}
我的解决方案是添加
$fsize = filesize($docFile);
header("Content-Length: ".$fsize);
感谢大家对的帮助
代码中有一些额外的空格会导致它失败。
尝试使用此代码:
$parts = pathinfo($doc);
$docFile = $userDocRoot . $doc;
if(!file_exists($docFile)){
throw new Exception('Can not find ' . $parts['basename'] . ' on server');
}
if($parts['extension'] == 'docx') {
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $parts['basename'] . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile($docFile);
} else {
header('Content-type: application/msword');
header('Content-Disposition: attachment; filename="' . $parts['basename'] . '"');
readfile($docFile);
}
如果仍然不起作用,请尝试注释掉header
和readfile
行,然后您将看到是否有任何错误。
此外,我建议您根据白名单检查文件名,这样人们就不能下载带有密码的PHP文件,等等。
我刚刚花了一段时间研究为什么我的DOCX文件被损坏,并偶然发现了这一点。。。但我也在其他地方找到了答案。。。
$fsize = filesize($docFile);
header("Content-Length: ".$fsize);
这给了我寻找的工具。。。关键是CCD_ 3需要文件的基本名称才能获得准确的文件大小!
调整我的代码:
header("Content-Length: ".filesize(basename($file)));
这现在提供了DOCX(我已将内容类型设置为"application/vnd.openxmlformats officedocument.wordprocessingml.docal"),而且我不必像其他人报告的那样"修复"文档。。。(我还发现修复有效)
这是一个对我有效的代码(经过大约5个小时的混乱):
// headers to send your file
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Length: " . filesize($original_file));
header('Content-Disposition: attachment; filename="' . $new_filename . '"');
ob_clean();
flush();
readfile($original_file);
exit;
我希望它能有所帮助:)
我遇到了同样的问题。
原因是,在我的php文件的某个地方隐藏了两个空格。
删除它们解决了问题。
- 在
header
和readfile-statements
前面添加"//
" - 在
readfile-statement.
之后写入echo "test";
- 然后查看HTML源代码,如果前面有空格"测试"