PHP 强制下载损坏的 .xlsx 文件

问题描述 投票:0回答:6

我正在开发一个允许教师上传文档和学生下载文档的网站。然而,有一个问题。 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;
php header download readfile
6个回答
4
投票

我遇到了这个问题,并且是 BOM

如何注意

unzip:用unzip检查输出文件,我在第二行看到一个警告。

$ 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 文件(我的意思是第一个

<?php
标签之前的 BOM)或库的先前输出。

你必须找到带有 BOM 的文件或命令在哪里,就我而言,现在,我没有时间找到它,但我用输出缓冲区解决了这个问题。

<?php
ob_start();

// ... code, includes, etc

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

2
投票

无论扩展名如何,这在我的本地 xampp 设置上都可以正常工作,因此从我的角度来看,不需要 case 语句,除非我丢失了某些东西

我已经用 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
投票

尝试:

<?
//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; 
?>

0
投票

试试这个:

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

0
投票

尝试添加额外的标头

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.