下载Microsoft Word和Excel文件的HTTP标头

13

如果我使用默认文件名下载 Microsoft Word,可以成功下载。但如果我使用 $变量 来命名,则文档扩展名将无法识别。

$No = 1; 
$Name = 'John'; 
$Test = 'Science';

//Download header
$document->save($doc);
header('Content-Description: File Transfer');
header('Content-Type: application/msword');
header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($doc));
ob_clean();
flush();
readfile($doc);

如果我将文件名更改为变量名,那么下载的文件将没有docx扩展名。有人能给些建议吗?

谢谢。

3个回答

21

正确的标题应该是

对于 Excel (*.xlsx) 文件:

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

针对 Word (*.docx):

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

为什么在Word中使用这个复杂的头部而不是application/zip - Marcelo
@MarceloRafael 你为什么会期望 application/zip 能够用于 Word 文档呢? - Jeff Lambert
2
因为它基本上是一个压缩文件。 - Richard
header("Content-Type : application/vnd.ms-excel") 也可以工作。 - bhavya_w

6

改变这个

header('Content-Type: application/msword');

to

header('Content-Type: application/octet-stream');

编辑:

并更改

header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");

to

header("Content-Disposition: attachment; filename=\"{$No}_{$Name}_{$Test}.docx\"");

我之前已经尝试过了。使用Firefox保存文档时,它不会给出文件扩展名,导致文件变成未知文件。 - JLearner
无效文件。我尝试了所有的方法,但似乎IE和Firefox对我成功下载带有文件扩展名的文件存在问题。 - JLearner
8
请更正您的错误纠正 - .docx 文件的 MIME 类型为 application/vnd.openxmlformats-officedocument.wordprocessingml.document,而 .xlsx 文件的 MIME 类型为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet。 - Mark Baker
4
@Parahat - http://technet.microsoft.com/en-us/library/ee309278.aspx 或者 http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/05/08/office-2007-open-xml-mime-types.aspx这是有关Office 2007 Open XML MIME类型的文章链接,提供了相关技术文档。 - Mark Baker
4
Finfo只是查看魔术文件以匹配签名,并仅在zipped文件中识别PK标题......它不会进一步查看实际压缩内容。http://serverfault.com/questions/338087/making-libmagic-file-detect-docx-files。官方MIME类型如我上面列出的,下载时应将其用于标头。 - Mark Baker

2

该头部的正确使用方法是:

Content-Disposition: attachment; filename="fname.ext" 注意,如果名称包含空格,则必须用引号括起来。

请参阅RFC6266第5节示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接