• php ZipArchive 文件压缩下载(多级文件夹压缩为指定文件夹)


    上节用到文件下载

    https://www.cnblogs.com/chaihy/p/11028880.html

    同理下载文件压缩下载

    <a herf="/upload?filename=''/upload/file/zip&new_filename=''bb">文件下载</a>

    参数new_filename 为zip名称

    参数filename 为要压缩文件夹(多级文件夹/upload/file/zip/)

    首先先检验要压缩文件夹是否存在 ,不然真的不存在会报错的

    if(file_exists($filename)){

    //得到zip地址

    $zip_file = $filename.'/'.$new_filename.'zip';

    //判断存在zip直接下载,不存在再压缩

        if(!file_exists($zip_file)){

            $zip = new ZipArchive();

            if($zip->open($zip_file,ipArchive::CREAT)==true){

                $this->addFileToZip($filename,$zip);

                $zip->close(); 

            }

        }

        //下载

     header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: Binary");
    header("Content-Length: " . filesize($zip_file));
    header("Content-Disposition: attachment; filename="" . basename($zip_file) . """);
    readfile($zip_file);

    }

    //压缩打包

    function addFileToZip(){

        $handler=opendir($path); //打开当前文件夹由$path指定。

        while(($filename=readdir($handler))!==false){

         if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作

            if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归
    $this->addFileToZip($path."/".$filename, $zip);
    }else{ //将文件加入zip对象
    $zip->addFile($path."/".$filename,$filename); // https://php.net/manual/zh/ziparchive.addfile.php 查看addFile函数
    }
    }
    }
    @closedir($path);

    }

    以上如有不懂请加群,如有疑问请留言

  • 相关阅读:
    JAVA设计模式之单例模式
    JAVA设计模式之单例模式
    数据库连接池
    数据库连接池
    DbUtils操作数据库
    DbUtils操作数据库
    Hadoop 问题之 Linux服务器jps报process information unavailable
    echarts ——纵坐标赋值
    echarts ——div没有设置样式图表就展示不出来!
    Elasticsearch+spring boot(一)
  • 原文地址:https://www.cnblogs.com/chaihy/p/11045245.html
Copyright © 2020-2023  润新知