所以这是有效的:
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 cannot open the file 'myfile.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
当我手动打开文件时(即没有通过链接下载它),文件可以正常打开
如果这很重要,我正在使用 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);
谢谢大家的回答。
最佳答案
取决于您的浏览器,很多事情都会导致这种行为,例如 Content-length 、Cache-Control 等
也改变
Content-type 到 Content-Type
Content-disposition 到 Content-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');
关于PHP xlsx header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198524/