基于Laravel,文件夹压缩下载

需求

  • 文件夹压缩成zip下载
  • laravel 8.x

知识点

  • php 中有一个类为ZipArchive
  • PHP ZIP 扩展已经开启

参考资料

       $path = public_path('word');
        $zipFileName = 'word.zip';
        $zip = new \ZipArchive;
        $zip->open($zipFileName, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); 
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
        foreach ($files as $name =>$file)
        {
         if (!$file->isDir()) {
          $filePath  = $file->getRealPath();
          $relativePath = 'word/' . substr($filePath, strlen($path) + 1);
          $zip->addFile($filePath, $relativePath);
         } 
        }
        
        $file_name = mb_convert_encoding($zipFileName,'GB2312','UTF-8');
        header('Content-type: application/zip');
        header("Content-Disposition: attachment; filename=\"{$file_name}\"");
        readfile(public_path($file_name));
        unlink(public_path($file_name));
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容