/**
* @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檔案
}
}
//遞回寫入壓縮包
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);
}
/**
* @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查看
}
$fp=fopen($path,"r");
$file_size=filesize($path);
//下載檔案需要用到的頭
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/251392.html
標籤:PHP
