企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 如何使用thinkPHP下载文件 > 注:thinkPHP版本为3.2.2 在thinkPHP的框架下实现文件下载功能可以通过Http.class.php类的download方法实现,类的路径为Thinkphp/Library/Org/Net/Http.class.php ![Http.class.php](https://box.kancloud.cn/3c268470179d6484bcd040b3d04ec580_286x460.PNG) #### download方法代码 ``` /** * 下载文件 * 可以指定下载显示的文件名,并自动发送相应的Header信息 * 如果指定了content参数,则下载该参数的内容 * @static * @access public * @param string $filename 下载文件名 * @param string $showname 下载显示的文件名 * @param string $content 下载的内容 * @param integer $expire 下载内容浏览器缓存时间 * @return void */ static public function download ($filename, $showname='',$content='',$expire=180) { if(is_file($filename)) { $length = filesize($filename); }elseif(is_file(UPLOAD_PATH.$filename)) { $filename = UPLOAD_PATH.$filename; $length = filesize($filename); }elseif($content != '') { $length = strlen($content); }else { E($filename.L('下载文件不存在!')); } if(empty($showname)) { $showname = $filename; } $showname = basename($showname); if(!empty($filename)) { $finfo = new \finfo(FILEINFO_MIME); $type = $finfo->file($filename); }else{ $type = "application/octet-stream"; } //发送Http Header信息 开始下载 header("Pragma: public"); header("Cache-control: max-age=".$expire); //header('Cache-Control: no-store, no-cache, must-revalidate'); header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT"); header("Content-Disposition: attachment; filename=".$showname); header("Content-Length: ".$length); header("Content-type: ".$type); header('Content-Encoding: none'); header("Content-Transfer-Encoding: binary" ); if($content == '' ) { readfile($filename); }else { echo($content); } exit(); } ``` #### 简单实现文件下载功能 ``` // 路径需要使用绝对路径 $url = 'C:/wenhsing'.__ROOT__.'/Upload/file/2018-04-10/filename.zip'; $http = new \Org\Net\Http; $http->download($url,'wenhsing.zip'); ``` #### 注意事项 问题 1. 文件下载后出现无法打开的情况,例如图片显示空白、压缩文件提示压缩文件损坏 > 解决方案: > 在头部文件信息声明之后,文件下载之前,添加两个函数,分别为 > ob_clean() 和 flush(); > ``` > header("Content-type: ".$type); > header('Content-Encoding: none'); > header("Content-Transfer-Encoding: binary" ); > ob_clean(); > flush(); > if($content == '' ) { > readfile($filename); > }else { > echo($content); > } > ``` 问题2. 访问出现Class 'finfo' not found错误 ![](https://box.kancloud.cn/88e3ece5c2fc654f9c53be0201696d0b_1360x619.png) > 解决方案: > PHP开启php_fileinfo扩展