php后端强制前端下载文件

来源:互联网 发布:ubuntu安装python2.7 编辑:程序博客网 时间:2024/06/05 06:07

点击一个<a>标签后下载一个文件


  /**
     * 输出文件流
     * @param $filePath  文件位置
     * @param null $downloadFileName 下载后显示的文件名
     */
    private function download_file($filePath, $downloadFileName = null) {
        if (file_exists($filePath)) {
            $downloadFileName = $downloadFileName !== null ? $downloadFileName : basename($filePath);
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . $downloadFileName);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filePath));

            ob_clean();//清空php的缓冲区
            flush();//清空web服务器的缓存区php的缓冲区超过限制php脚本还没有结束就会输出到服务器的缓存区或者浏览器的缓冲区  清除他?
            readfile($filePath);
            exit;
        }else{
            redirect($_SERVER['HTTP_REFERER']);//看业务逻辑  这里是如果文件不存在  避免调到空白页面
        }

    }