说明:
参数检查:首先会检查文件是否存在,如果不存在,会返回 404 错误。
文件头部设置:设置必要的 HTTP 头,通知浏览器进行文件下载,并设置文件名、MIME 类型和文件大小。
流式读取文件:以流的方式一次读取 8KB 的内容,避免占用太多内存,特别适合下载大文件。
缓存处理:调用
ob_clean()
和flush()
清除 PHP 缓冲区,确保没有多余的输出干扰下载。错误处理:如果文件读取出错,则返回 500 错误。
你可以将这个接口集成到你的应用中,通过 URL 参数传入文件路径,或者根据实际需求对文件进行选择。
<?php function streamDownload($filePath) { // 检查文件是否存在 if (!file_exists($filePath)) { header("HTTP/1.1 404 Not Found"); echo "File not found."; return; } // 获取文件信息 $fileName = basename($filePath); // 获取文件名 $fileSize = filesize($filePath); // 获取文件大小 ////$mimeType = mime_content_type($filePath); // 获取文件的MIME类型 // 设置响应头,通知浏览器进行下载 header('Content-Description: File Transfer'); ////header('Content-Type: ' . $mimeType); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Content-Length: ' . $fileSize); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Expires: 0'); // 清除缓冲区以避免意外输出 ob_clean(); flush(); // 以流方式读取文件并输出 $file = fopen($filePath, 'rb'); if ($file) { while (!feof($file)) { echo fread($file, 1024 * 8); // 每次读取8KB flush(); // 强制刷新缓冲区 } fclose($file); } else { header("HTTP/1.1 500 Internal Server Error"); echo "Error reading file."; } } // 示例调用 $filePath = 'path/to/your/file.zip'; // 替换为实际的文件路径 streamDownload($filePath);