控制器
<?phpnamespace app\api\controller;
use think\Controller;
use think\facade\Db;
use think\facade\Request;use ZipArchive;class DrugTestResult
{public function download(){if(Request::isPost()){$data = Request::post();$idnumber = Request::param('idnumber');$info = Db::name('drug_test_result')->where('idnumber',$idnumber)->where('is_delete',1)->find();if($info){// 创建压缩临时目录mkdir('download/'.$idnumber, 0777, true);// 压缩的文件夹路径$folderPath = 'download/'.$idnumber;// 压缩后的 ZIP 文件路径$zipFilePath = 'download/'.$idnumber.'.zip';// 创建 ZipArchive 实例$zip = new ZipArchive();if ($zip->open($zipFilePath, ZipArchive::CREATE) === true) {//查询压缩的文件列表$images = Db::name('drugimg')->where('id','in',$info['image'])->select()->ToArray();foreach ($images as $k => $v){#源文件夹$fileDir = '/www/wwwroot/abcapi/public/'.$v['thumb']; #目标文件夹$tarDir = '/www/wwwroot/abcapi/public/download/'.$idnumber.'/'.$v['title']; //复制到临时文件夹copy($fileDir,$tarDir);}$files = scandir($folderPath);foreach ($files as $file) {// 排除当前目录和上级目录if ($file != '.' && $file != '..') {$filePath = $folderPath . '/' . $file;$relativePath = basename($file);$zip->addFile($filePath);}}$zip->close();//删除临时文件夹deleteFolder('/www/wwwroot/abcapi/public/'.$folderPath.'/');//返回压缩包地址(接口)echo apireturn(200,200,'success','/'.$zipFilePath);die;// 设置响应头,告诉浏览器下载文件// header("Content-Type: application/zip");// header("Content-Disposition: attachment; filename=\"" . basename($zipFilePath) . "\"");// header("Content-Length: " . filesize($zipFilePath));// 读取并输出压缩文件内容//readfile($zipFilePath);// 删除临时 ZIP 文件//unlink($zipFilePath);} else {echo apireturn(200,201,'faild','');die;}}else{echo apireturn(200,201,'文件不存在或已被删除','');die;}}}
}
这里我采用的是php自带的ZipArchive类
需要先确认php.ini配置文件中是否取消注释了extension=zip和extension=openssl 来启用这些扩展
公共函数
/*** 通用化API输出格式* @param integer $status http状态码* @param string $code 业务状态码* @param string $msg 消息内容* @param array $data 数据* @return json 返回json格式的数据*/
function apireturn($status,$code,$msg,$data){$data_rt['status'] = $status;$data_rt['code'] = $code;$data_rt['msg'] = $msg;if(is_array($data)){if(!empty($data)){$data_rt['data'] = $data;}else{$data_rt['data'] = array();}}else{if(!empty($data)){$data_rt['data'] = $data;}else{$data_rt['data'] = array();}}return json_encode($data_rt,TRUE);
}//删除文件
function deleteFolder($folderPath) {if (is_dir($folderPath)) {if (is_dir_empty($folderPath)) {rmdir($folderPath);} else {// 文件夹不为空,先删除其中所有文件和文件夹$files = scandir($folderPath);foreach ($files as $file) {if ($file != "." && $file != "..") {$filePath = $folderPath . "/" . $file;if (is_dir($filePath)) {deleteFolder($filePath);} else {unlink($filePath);}}}// 删除完子文件和子文件夹后再删除空文件夹rmdir($folderPath);}}
}function is_dir_empty($folderPath) {$files = scandir($folderPath);return count($files) <= 2;
}