如何使用PHP下载存储在storage目录中的Excel文件
PHP实现storage目录Excel文件下载方案
1. 前端按钮配置
直接添加指向PHP下载处理接口的按钮/链接即可:
<a href="download_excel.php">下载Excel</a>
如果需要用button标签触发,也可以绑定click事件跳转到对应接口地址。
2. 后端PHP处理逻辑
新建download_excel.php文件,写入以下代码:
<?php // 替换为实际的Excel文件绝对路径 $excel_file = __DIR__ . '/storage/目标文件.xlsx'; // 校验文件是否存在及可读 if (!file_exists($excel_file) || !is_readable($excel_file)) { die("请求的文件不存在或无读取权限"); } // 处理中文文件名乱码问题 $filename = basename($excel_file); $encoded_filename = rawurlencode($filename); // 设置下载响应头 // xls格式请将Content-Type替换为 application/vnd.ms-excel header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename*=UTF-8\'\'' . $encoded_filename); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Content-Length: ' . filesize($excel_file)); // 输出文件内容 readfile($excel_file); exit; ?>
注意事项
- 优先使用绝对路径定位文件,避免相对路径读取失败
- 确保PHP运行进程对storage目录和目标Excel文件有读取权限
- 若storage目录为非Web公开目录也可正常使用,该方案不需要文件本身对外暴露可访问
内容的提问来源于stack exchange,提问作者echobash
相关产品推荐
相关产品推荐

