Thinkphp框架下封装文件下载函数

第一步:开启php_fileinfo.dll

方法:打开php.ini,将874行的;extension=php_fileinfo.dll前面的分号注释去掉即可;

第二步:控制层封装文件下载函数

function download_file($file){
    if(is_file($file)){
        $length = filesize($file); //文件大小
        $type = mime_content_type($file); //文件类型
        $showname =  ltrim(strrchr($file,'/'),'/'); //文件名
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
         if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
             header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
         } else {
             header('Content-Disposition: attachment; filename="' . $showname . '"');
         }
         readfile($file);
         exit;
     } else {
         exit('文件已被删除!');
     }
 }

其中$file为文件的绝对路径,在view层点击下载文件按钮,传入控制层即可;

原文地址:https://www.cnblogs.com/wenzheshen/p/7245643.html