ThinkPHP框架下如何用PHP自带的ZipArchive类打包压缩文件

public function downloadzip(){
$catid = $this->request->param('catid/d', 0);
$id = $this->request->param('id/d', 0);
$category = getCategory($catid);
if (empty($category)) {
$this->error('该栏目不存在!');
}
$modelid = $category['modelid'];
$fieldList = $this->Cms_Model->getFieldList($modelid, $id);

$attatchs=$fieldList['uploadmaterial']['value'];

$attatchsarray=explode(',',$attatchs);
$zip=new \ZipArchive();
$downpath=[];
$timefils=date("Ymd",time());
if(!file_exists('uploads/zip/'.$timefils)){
mkdir ('uploads/zip/'.$timefils,0777,true);
}

$zipName ='uploads/zip/'.$timefils.'/download'.$id.'.zip';

if($zip->open($zipName,\ZipArchive::OVERWRITE | \ZipArchive::CREATE)==TRUE){
foreach($attatchsarray as $key=>$value){
$downpath=dirname(ROOT_PATH).get_file_path($value);
$downpathname=get_file_name($value); //改文件一定得为本地地址不可以为域名地址
$zip->addFile($downpath, basename($downpathname)); //basename($downpathname)这个是压缩包里面的文件名称

}
}
$zip->close();

if(!file_exists($zipName)){
$this->error('文件创建失败');
}
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipName);
header('Content-Length: ' . filesize($zipName));//文件大小
readfile($zipName);
}

posted @ 2019-08-22 18:23  敲敲敲代码  阅读(1913)  评论(0编辑  收藏  举报