PHP:发送WORD文档文件下载

时间:2012-07-17 08:18:57

标签: php file ms-word download content-disposition

这个问题很简单,并且有很多答案,都是相同或接近但是对于我的情况,它并没有像预期的那样解决? 目标:使用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 ...

但如果我从服务器打开原件,一切都还可以。 我错过了明显的东西...... 任何建议都是受欢迎的,因为我尝试了几乎所有我读过的方法......但结果仍然相同。

3 个答案:

答案 0 :(得分:2)

也许你的输出文件出错了标题。我的脚本中有类似的东西,我用来下载文件:

$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'] );

我从db。

获取的文件名

答案 1 :(得分:2)

从您显示的内容的几个字符开始,您创建的是OfficeOpenXML(.docx)文件而不是BIFF(.doc)文件,因此内容类型应为

application/vnd.openxmlformats-officedocument.wordprocessingml.document

,文件扩展名应为.docx

答案 2 :(得分:-1)

致电https://stackoverflow.com/download-script.php?file=example.doc

这是download-script.php代码

if (isset($_GET['file'])) {    
  $file = $_GET['file'];

  if (file_exists($file) && is_readable($file) && preg_match('/\.doc$/',$file)) {
    header('Content-Type: application/doc');
    header("Content-Disposition: attachment; filename=\"$file\"");

    readfile($file);
  }    
} else {
  header("HTTP/1.0 404 Not Found");

  echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}