PHP实现文件下载

简单的示例代码:

function downloadFile($filePath)
{

    set_time_limit(0);

    if (substr($filePath, strlen($filePath) - 1) == '/') {
        $filePath = substr($filePath, 0, strlen($filePath) - 1);
    }

    if (!is_file($filePath) && !is_readable($filePath)) {
        return false;
    }
    $obj = new SplFileInfo($filePath);
    header('Content-Type: application/octet-stream');
    header('Accept-Ranges:bytes');
    header('Content-Length:' . filesize($filePath)); //注意是'Content-Length:' 非Accept-Length
    header('Content-Disposition:attachment;filename=' . $obj->getFilename());//声明作为附件处理和下载后文件的名称

    $buffer = 1024;
    ob_clean();
    $handle = fopen($filePath, 'rb');
    while (!feof($handle)) {
        echo fread($handle, $buffer);
    }
    flush();
    fclose($handle);
    exit;

}

主要是设置header头:

文件类型:Content-Type: application/octet-stream

字节流:Accept-Ranges:bytes

长度:Content-Length:>0

声明作为附件处理和下载后文件的名称:

Content-Disposition:attachment;filename=FILENAME

 

*最重要的是 ob_clean();跟flush();

如果没有这两个函数,有可能下载下来的文件就是损坏的。

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |