打包下载和上传ZIP

一、html端

<a href="javascript:;" class="btn btn-success btn-import {:$auth->check('p5129/baoming/import')?'':'hide'}" title="{:__('导入')}" ><i class="fa fa-plus"></i> {:__('导入证书ZIP')}</a>
<a href="/dabao.html?bsid={$bsid}" target="_blank" class="btn btn-danger btn-more"><i class="fa fa-cog"></i> {:__('作品打包')}</a>

二、打包下载

public function dabao(){
	$server=request()->server();
	$zip = new \ZipArchive;
	$filename = $server['DOCUMENT_ROOT'].'/uploads/'.Random::alnum(10).'.zip';
	$bsid = $this->request->param('bsid');
	$zip->open($filename,\ZIPARCHIVE::OVERWRITE | \ZIPARCHIVE::CREATE);
	$baoming = Db::name("kycms_baoming")->where(['kycms_bisai_id'=>$bsid])->select();
	foreach($baoming as $v){
	$files = Db::name("kycms_baoming_dzd")->where(['kycms_baoming_id'=>$v['id'],'status'=>1])->select();
	foreach($files as $file){
	$xx=$zip->addFile($server['DOCUMENT_ROOT'].$file['filename'],basename($file['filename']));
	}
	}
	$zip->close();
	header("Cache-Control: public");
	header("Content-Description: File Transfer");
	header('Content-disposition: attachment; filename='.basename($filename));
	header("Content-Type: application/zip");
	header("Content-Transfer-Encoding: binary");
	header('Content-Length: '.filesize($filename));
	readfile($filename);
}

三、打包上传解压

public function import()
	{
		$server=request()->server();
		//D:/fastadmin/2024/p5129/public
		//echo $server['DOCUMENT_ROOT'];die;
		$file = $this->request->request('file');
		$targetPath = basename($file,'.zip');
		if (!is_dir($targetPath)) {
			mkdir($server['DOCUMENT_ROOT']."/".$targetPath, 0777, true);
		}
		
		
		Db::startTrans();
		try{
			$bsid = $this->request->param("bsid");
			
			$zip = new \ZipArchive();
			$res = $zip->open($server['DOCUMENT_ROOT']."/".$file);
			if ($res) {
				$zip->extractTo($server['DOCUMENT_ROOT']."/".$targetPath);
				$extracted_folder_name = $targetPath . '/' . pathinfo($file, PATHINFO_FILENAME);

				$files = @scandir($server['DOCUMENT_ROOT']."/".$targetPath);
				foreach($files as $v){
					if($v!='.' && $v!='..'){
						$arr = explode(".",$v);
						if(isset($arr[0])){
							$filename= '/'.trim($targetPath).'/'.trim($v);
							Db::name("kycms_baoming")->where(['bianhao'=>$arr[0]])->update(['file'=>$filename]);
						}
					}
				}
				Db::commit();
				$this->success("上传成功");
			}else{
				$this->error("上传失败");
			}
			
		} catch (ValidateException $e) {
			Db::rollback();
			$this->error($e->getMessage());
		} catch (PDOException $e) {
			Db::rollback();
			$this->error($e->getMessage());
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

	}

发表评论