/**
* @param $path 要壓縮的文件夾路徑
* @param $filename 要生成的壓縮包名稱
*/
public function create_zip($path,$filename) {
$zip = new \ZipArchive();
if($zip->open($filename.'.zip', \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {
$this->addFileToZip($path, $zip);//調用方法,對要打包的根目錄進行操做,並將ZipArchive的對象傳遞給方法
$zip->close(); //關閉處理的zip文件
}
}html
//遞歸寫入壓縮包
public function addFileToZip($path,$zip) {
$handler = opendir($path); //打開當前文件夾由$path指定。
while (($filename = readdir($handler)) !== false) {
if ($filename != "." && $filename != "..") { //文件夾文件名字爲'.'和‘..’,不要對他們進行操做
if (is_dir($path . "/" . $filename)) {
$this->addFileToZip($path . "/" . $filename, $zip);
} else {
$zip->addFile($path . "/" . $filename);
}
}
}
@closedir($path);
}ajax
/**
* @param $path 要下載的文件路徑
* @param $filename 保存的文件名
*/
public function downloadTemplate($path,$filename){服務器
header("Content-type:text/html;charset=utf-8");
if(!file_exists($path)){
echo "下載文件不存在!";exit; //若是提示這個錯誤,極可能你的路徑不對,能夠打印$file_sub_path查看
}app
$fp=fopen($path,"r");this
$file_size=filesize($path);spa
//下載文件須要用到的頭.net
Header("Content-type: application/octet-stream");code
Header("Accept-Ranges: bytes");htm
Header("Accept-Length:".$file_size);對象
Header("Content-Disposition: attachment; filename=".$filename);
$buffer=1024;
$file_count=0;
while(!feof($fp) && $file_count<$file_size){
$file_con=fread($fp,$buffer);
$file_count+=$buffer;
echo $file_con;
}
fclose($fp); //關閉這個打開的文件
unlink($path); //刪除服務器壓縮文件,釋放服務器資源
}
$path = 'qrcode/'.$pid.'/'.date('Y-m-d'); //服務器文件路徑
$filename = 'qrcode/'.$pid.'/'.date('Y-m-d'); //想要生成的壓縮包
//開始壓縮文件而且下載到本地
$this->create_zip($path,$path); //我這裏生成的壓縮包放在同一個目錄下面 就不搞多一個路徑 + 文件名了
$this->downloadTemplate($filename.'.zip',$pid.date('Y-m-d').'.zip'); // !!!!切記 下載文件不要用ajax 下載文件不要用ajax 下載文件不要用ajax 重要的事情說三遍!
效果圖:
感謝 整合於https://blog.csdn.net/s_hooligan/article/details/94627095 https://blog.csdn.net/hexiaoniao/article/details/89222983