这个问题很简单,有很多答案,全部相同或几乎相同,但对于我的情况,它没有按预期解决? 目标:使用 PHP 发送 WORD 文件作为附件(简单...) 意思是:这是代码:
// send the file to the browser
header("Cache-Control: no-store");
header("Content-Type: application/octet-stream");
//header("Content-type: application/msword");
header('Content-Disposition: attachment; filename="'. basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. filesize($filename));
ob_clean();
flush();
readfile($filename);
exit();
好吧,一切似乎都正确,但我保存在计算机上的文件无法被 MS-WORD 读取:它读取一些特殊字符,如:
PK ! /Œt1« á [Content_Types].xml ...
但是如果我从服务器打开原件,一切正常。 我错过了一些明显的东西...... 欢迎任何建议,因为我几乎尝试了所有阅读的方法...但结果仍然相同。
最佳答案
也许您的输出文件 header 有误。我的脚本中有类似这样的东西,我用它来下载文件:
$tmp = explode(".",$file['filename']);
switch ($tmp[count($tmp)-1]) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "docx":
case "doc": $ctype="application/msword"; break;
case "csv":
case "xls":
case "xlsx": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
case "tif":
case "tiff": $ctype="image/tiff"; break;
case "psd": $ctype="image/psd"; break;
case "bmp": $ctype="image/bmp"; break;
case "ico": $ctype="image/vnd.microsoft.icon"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( 'files/'.$file['filename'] );
我从数据库中获取的文件名。
关于PHP:发送WORD文档文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518576/