2

这个问题是微不足道的,有很多答案,都一样或几乎一样,但就我而言,它没有按预期解决?目标:使用 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 ...

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

4

3 回答 3

2

也许您的 uotput 文件的标题错误。我的脚本中有类似的东西,我用它来下载文件:

$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 获取的文件名。

于 2012-07-17T08:30:02.530 回答
2

从您显示的内容的几个字符中,您正在创建一个 OfficeOpenXML (.docx) 文件而不是 BIFF (.doc) 文件,因此内容类型应该是

application/vnd.openxmlformats-officedocument.wordprocessingml.document

并且文件扩展名应该是 .docx

于 2012-07-17T08:30:54.737 回答
-1

调用https://stackoverflow.com/download-script.php?file=example.doc

这是下载-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>";
}
于 2015-05-29T06:41:54.123 回答