PHP强制下载.xlsx文件损坏

时间:2012-12-18 17:18:27

标签: php header download readfile

我正在开发一个网站,允许教师上传文件,学生可以下载文件。但是,有一个问题。 Microsoft Word(.docx)文件下载完美,但下载excel(xlsx)文件时,excel会显示“此文件已损坏且无法打开”对话框。任何有关这方面的帮助将不胜感激!

我的下载代码如下:

case 'xlsx':

    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Pragma: no-cache');
    readfile('./uploads/resources/courses/' . $filename);

break;

6 个答案:

答案 0 :(得分:2)

这在我的本地xampp设置上运行正常,无论扩展如何,所以从我的角度来看,除非我遗漏了某些内容,否则不需要大小写声明

我已经测试过docx,accdb,xlsx,mp3,等等......

$filename = "equiv1.xlsx";

header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Pragma: no-cache');

答案 1 :(得分:2)

我有这个问题,是BOM

如何注意

解压缩:使用解压缩检查输出文件,我在第二行看到了警告。

$ unzip -l file.xlsx 
Archive:   file.xlsx
warning file:  3 extra bytes at beginning or within zipfile
...

xxd(十六进制查看器):我使用以下命令看到前5个字节

head -c5 file.xlsx | xxd -g 1
0000000: ef bb bf 50 4b                             PK...

注意3个第一个字节ef bb bf的BOM!

为什么?

可能是带有BOM的php文件或来自库的先前输出。

你必须找到带有BOM的文件或命令的位置,在我的情况下,现在,我没有时间找到它,但我用输出缓冲区解决了这个问题。

<?php
ob_start();

// ... code, includes, etc

ob_get_clean();
// headers ...
readfile($file);

答案 2 :(得分:0)

试试这个:

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");

答案 3 :(得分:0)

尝试:

<?
//disable gzip
@apache_setenv('no-gzip', 1); 
//set download attachment
header('Content-Disposition: attachment;filename="filename.xlsx"');
//clean the output buffer 
ob_clean(); 
//output file
readfile('filepath/filename.xlsx');
//discard any extra characters after this line
exit; 
?>

答案 4 :(得分:0)

尝试添加其他标题

header('Content-Length: ' . filesize('./uploads/resources/courses/' . $filename));

答案 5 :(得分:0)

可能是Windows提供的非常误导性信息,与代码,Excel库或服务器无关,文件本身就是正确的文件。 Windows阻止打开一些从Internet下载的文件(例如.xlsx),而不是询问是否要打开不安全的文件,它只是写出该文件已损坏。在Windows 10中,需要右键单击该文件,然后选择“ 取消阻止”(例如,您可以在此处阅读更多信息:https://winaero.com/blog/how-to-unblock-files-downloaded-from-internet-in-windows-10/

相关问题