php压缩文件夹并下载到本地

 

 

/**
* @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

相关文章
相关标签/搜索