laravel5以上使用zipper操作文件压缩解压

使用前提:laravel 版本必须大于 5
1、使用 composer 引入

composer require chumper/zipper

2、配置 app/config/app.php

'providers'=>[
    Chumper\Zipper\ZipperServiceProvider::class
]
 'aliases' => [
    'Zipper' => Chumper\Zipper\Zipper::class
]

3、压缩文件
***** 必须使用 use 引文文件

    use Chumper\Zipper\Zipper;
    $number=1;
    $zip=new Zipper();
    $newName='group_'.$number.'.zip';
    $zip->make(public_path('vdieoZip/'.$newName))->add($res);
    $zip->close();
    return response()->download(public_path('vdieoZip/'.$newName));

4、解压文件
***** 必须使用 use 引文文件

    use Chumper\Zipper\Zipper;
    $zip = new Zipper();
    $zip->make(压缩的文件目录)->extractTo(压缩之后的目录);

5:遍历文件打包至压缩包

    $files = Array();
            foreach ($student as $key => $data) {
                if ($data->photopath != null) {
                    $check = glob(storage_path('photo/' . $data->photopath));
                    $files = array_merge($files, $check);
                }
            }
     Zipper::make(storage_path() . '/systemImg/' . $name)->add($files)->close();

6:读取压缩包文件

       Zipper::make( storage_path() . '/photo/photos')->extractTo(storage_path('temp'));
      $zip = new \ZipArchive();//方法2:流处理,新建一个ZipArchive的对象
                    $logFiles = Zipper::make($path)->listFiles('/\.png$/i');
                    if ($zip->open($path) === TRUE) {
                        foreach ($logFiles as $key) {
                            $stream = $zip->getStream($key);
                            $str = stream_get_contents($stream); //这里注意获取到的文本编码
                            $name = iconv("utf-8", "gb2312//IGNORE", $key);
                            file_put_contents(storage_path() . '\temp\\' . $name, $str);
                        }
                    } else {
                        return '{"statusCode":"300", "message":"上传失败,请检查照片"}';
                    }

 

文件来源: https://learnku.com/articles/16000 

你可能感兴趣的:(php,laravel)