这样可行:
myphpfile.php:
<?php
header('Content-disposition: attachment; filename=myfile.pdf');
header('Content-type: application/pdf');
readfile('myfile.pdf');
?>
Run Code Online (Sandbox Code Playgroud)
在这里调用php文件,PDF下载工作正常:
<a class = "oglasavanje" href = "../../cjenik/myphpfile.php">download</a><br/>
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
<?php
header('Content-disposition: attachment; filename=myfile.xlsx');
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
readfile('myfile.xlsx');
?>
Run Code Online (Sandbox Code Playgroud)
.pdf和.xlsx文件都在同一个文件夹中.当我点击"下载"链接弹出下载窗口时,我保存文件,但无法打开该文件.它给了我以下错误:
Excel无法打开文件'myfile.xlsx',因为文件格式或文件扩展名无效.验证文件是否已损坏,以及文件扩展名是否与文件格式匹配.
当我手动打开文件时(即不通过链接下载),文件打开正常
我正在使用WAMP,如果这很重要的话.
任何帮助表示赞赏.
---编辑---
我在php.net上找到了这段代码:
ob_clean();
flush();
Run Code Online (Sandbox Code Playgroud)
所以最终的代码看起来像这样,它的工作原理:
$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);
Run Code Online (Sandbox Code Playgroud)
谢谢大家的答案.
取决于你的浏览器,因此很多事情可能会导致这样的行为,如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');
Run Code Online (Sandbox Code Playgroud)
小智 2
根据您的网络浏览器,文件名可能无法完整保存并带有句点。如果文件名不完整,您可以尝试替换此标头:
header('Content-disposition: attachment; filename=myfile.xlsx');
Run Code Online (Sandbox Code Playgroud)
和
$filename = "myfile.xlsx";
header('Content-Disposition: attachment; filename="' . $filename . '"');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50506 次 |
| 最近记录: |