php - php网站显示文件而不是下载
问题描述
我在 Azure 的 linux Web 应用服务上运行 php 8 网站。当用户按下按钮时,我想动态创建一个文件(从 db 读取数据)并下载它。相反,它在页面上显示内容。这是代码
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=geodata.csv");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("geodata.csv"));
$file = fopen('php://output', 'w')
or die ("Unable to create file in write mode");
if (ob_get_contents()) ob_end_clean();
fputcsv($output, array('name','loc','zip'), chr(6));
$mrows = mysqli_query($myconnection, "SELECT name,loc,zip FROM geo_tbl WHERE sp = 'FL'");
while ($mrow = mysqli_fetch_assoc($mrows)) {
fputcsv($file, $mrow, chr(6));
}
fclose($file);
readfile("geodata.csv");
exit();
谢谢
解决方案
当用户按下按钮时
只需将下载属性添加到您的按钮,它应该可以立即工作。
<a href="link/to/your/file.csv" download="filename.csv">Download link</a>
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download
推荐阅读
- javascript - 在 javascript 中使用单选按钮禁用页面的一部分
- iis - 使用 4 台计算机进行安全数据传输(共享文件夹、代理、WebDav/SFTP)
- amazon-web-services - 如何减少请求产生的“连接”时间
- javascript - 使用适用于 JavaScript V3 的 AWS 开发工具包直接从浏览器将消息发布到 SNS
- flutter - Flutter blocTest 返回空的“实际”数组
- apache-spark - 如何更改作为 gcr.io/spark-operator/spark:v3.0.0-hadoop3 扩展的 spark-operator 映像中的 prometheus jmx 导出器规则
- angular - Angular iframe 无法使用 DomSanitizer 快速加载 url
- python - 在 Python 中创建带有电子邮件附件的数组
- spring-boot - 从 Consul 读取应用程序属性
- r - 'mitml'-package:是否有可能在具有二元结果变量的多级逻辑回归输出中获得 ICC?