一个php流式下载文件的接口示例

说明:

  1. 参数检查:首先会检查文件是否存在,如果不存在,会返回 404 错误。

  2. 文件头部设置:设置必要的 HTTP 头,通知浏览器进行文件下载,并设置文件名、MIME 类型和文件大小。

  3. 流式读取文件:以流的方式一次读取 8KB 的内容,避免占用太多内存,特别适合下载大文件。

  4. 缓存处理:调用 ob_clean()flush() 清除 PHP 缓冲区,确保没有多余的输出干扰下载。

  5. 错误处理:如果文件读取出错,则返回 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);


发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2024年10月    »
123456
78910111213
14151617181920
21222324252627
28293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
    网站收藏
    友情链接

    Powered By Z-BlogPHP 1.7.3

    Copyright Your xin1234.com Rights Reserved.