PHP服务端PDF、JPG/JPEG等文件下载功能失效问题咨询
问题根因
你遇到的问题核心由两个常见的PHP下载逻辑错误导致:
- 使用了非标准的
Content-Type: application/force-download头,Chrome、Edge等现代浏览器会对PDF、图片这类自带预览能力的资源忽略该头,直接触发内置渲染逻辑 - 现有代码仅发送了下载头,没有输出实际的文件内容,同时未终止后续程序执行,导致浏览器等待内容超时后,将接收到的零散数据流直接当成页面内容解析展示
修复方案
1. 替换Content-Type为标准MIME类型
根据文件后缀匹配正确的MIME类型,避免浏览器强制渲染:
$mimeMap = [ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'pdf' => 'application/pdf', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'txt' => 'text/plain' ]; // 替换原来的application/force-download行 header("Content-Type: " . $mimeMap[$file_extension]);
2. 发送头前清空输出缓冲区,避免异常输出
在发送所有header前添加以下代码,清除之前的意外输出(比如PHP文件首尾的空格、BOM头、调试输出等):
ob_clean(); ob_start();
3. 补充文件输出逻辑,执行完后终止程序
在flush();之后添加读取输出文件、终止执行的代码:
readfile($downloadFile); exit;
完整可运行的下载逻辑示例
$downloadFile = 'openFiles/'.$path; file_put_contents($downloadFile, $decrypted_code); $file_extension = strtolower(end(explode('.', $path))); // 允许的后缀校验你已实现,此处省略 $mimeMap = [ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'pdf' => 'application/pdf', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'txt' => 'text/plain' ]; // 清空输出缓冲区 ob_clean(); ob_start(); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header('Content-Description: File Transfer'); // 使用正确的MIME类型 header("Content-Type: " . $mimeMap[$file_extension]); header("Content-Disposition: attachment; filename=\"".basename($downloadFile)."\";"); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($downloadFile)); flush(); // 输出文件内容 readfile($downloadFile); // 终止后续执行 exit;
内容的提问来源于stack exchange,提问作者Svitlana Kuievda
相关产品推荐
相关产品推荐

