Laravel 中创建 Zip 压缩文件并提供下载的实现方法分享!

如果您需要您的用户支持多文件下载的话,最好的办法是创建一个压缩包并提供下载。下面通过本文给大家看下在 Laravel 中的实现。

事实上,这不是关于 Laravel 的,而是和 PHP 的关联更多,我们准备使用从 PHP 5.2 以来就存在的 ZipArchive 类 ,如果要使用,需要确保php.ini 中的 ext-zip 扩展开启。

任务 1: 存储用户的发票文件到 storage/invoices/aaa001.pdf

下面是代码展示:

  $zip_file = 'invoices.zip'; // 要下载的压缩包的名称  // 初始化 PHP 类  $zip = new ZipArchive();  $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);  $invoice_file = 'invoices/aaa001.pdf';  // 添加文件:第二个参数是待压缩文件在压缩包中的路径  // 所以,它将在 ZIP 中创建另一个名为 "storage/" 的路径,并把文件放入目录。  $zip->addFile(storage_path($invoice_file), $invoice_file);  $zip->close();  // 我们将会在文件下载后立刻把文件返回原样  return response()->download($zip_file);

例子很简单,对吗?

*

任务 2: 压缩 全部 文件到 storage/invoices 目录中

Laravel 方面不需要有任何改变,我们只需要添加一些简单的 PHP 代码来迭代这些文件。

  $zip_file = 'invoices.zip';  $zip = new ZipArchive();  $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);    $path = storage_path('invoices');  $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));  foreach ($files as $name => $file)  {   // 我们要跳过所有子目录   if (!$file->isDir()) {    $filePath  = $file->getRealPath();      // 用 substr/strlen 获取文件扩展名    $relativePath = 'invoices/' . substr($filePath, strlen($path) + 1);      $zip->addFile($filePath, $relativePath);   }  }  $zip->close();  return response()->download($zip_file);

到这里基本就算完成了。你看,你不需要任何 Laravel 的扩展包来实现这个压缩方式。

PS:下面看下laravel从入门到精通之 文件处理 压缩/解压zip

1:将此软件包添加到所需软件包列表中composer.json

"chumper/zipper": "1.0.x"

2:命令行执行

composer update

3:配置app/config/app.php

  add to providers ChumperZipperZipperServiceProvider::class  add to aliases 'Zipper' => ChumperZipperZipper::class

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

  $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();

5:读取压缩包文件

    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":"上传失败,请检查照片"}';          }

总结

以上所述是小编给大家介绍的Laravel 中创建 Zip 压缩文件并提供下载的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对<计算机技术网(www.ctvol.com)!!>网站的支持!

—-想了解Laravel 中创建 Zip 压缩文件并提供下载的实现方法分享!且更多的php教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/phpttorial/481428.html

(0)
上一篇 2020年11月10日
下一篇 2020年11月10日

精彩推荐