8

所以这有效:

myphpfile.php:

<?php
header('Content-disposition: attachment; filename=myfile.pdf');
header('Content-type: application/pdf');
readfile('myfile.pdf');
?> 

此处调用该 php 文件,并且 PDF 下载工作正常:

<a class = "oglasavanje" href = "../../cjenik/myphpfile.php">download</a><br/>

但这不起作用:

<?php
header('Content-disposition: attachment; filename=myfile.xlsx');
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
readfile('myfile.xlsx');
?>

.pdf 和 .xlsx 文件都在同一个文件夹中。当我单击“下载”链接时,会弹出下载窗口,我保存文件,但无法打开文件。它给了我以下错误:

Excel 无法打开文件“myfile.xlsx”,因为文件格式或文件扩展名无效。验证文件没有损坏并且文件扩展名与文件格式匹配。

当我手动打开文件时(即不通过链接下载)文件打开正常

如果这很重要,我正在使用 WAMP。

任何帮助表示赞赏。

- - 编辑 - -

我在 php.net 上找到了这段代码:

ob_clean();
flush();

所以最终的代码看起来像这样并且它可以工作:

$file = "myfile.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
flush(); 
readfile($file);

谢谢大家的回答。

4

4 回答 4

7

取决于您的浏览器,很多事情都可能导致此类行为,例如Content-lengthCache-Control

也改变

Content-typeContent-Type

Content-dispositionContent-Disposition

尝试

$file = "myfile.xlsx" ;
header('Content-Disposition: attachment; filename=' . $file );
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('myfile.xlsx');
于 2012-04-17T20:39:32.017 回答
1

根据您的 Web 浏览器,文件名可能无法完全保存并带有句点。如果文件名不完整,您可以尝试替换此标头:

header('Content-disposition: attachment; filename=myfile.xlsx');

$filename = "myfile.xlsx";
header('Content-Disposition: attachment; filename="' . $filename . '"');
于 2012-04-17T20:28:04.707 回答
1
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($filename);
return;

该解决方案对我有用,但是当我尝试打开下载的文件时出现错误。对于 .pdf 文件只是空的。

于 2016-02-04T15:14:36.640 回答
0
$file = "abc.xls";

header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
于 2021-07-09T09:12:34.430 回答