Laravel 中创建 Zip 压缩文件并提供下载的实现方法
若需支持用户一次性下载多个文件,最佳方案是将其打包为压缩包供其获取。以下将展示在 Laravel 环境下的具体实现步骤。
该功能核心依赖于 PHP 原生机制而非 Laravel 特有逻辑。我们将采用自 PHP 5.2 起便已存在的 ZipArchive 类,使用前请确认 php.ini 中已启用 ext-zip 扩展。
任务一:将用户的发票文件存储至 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);
上述示例逻辑简单直观,对吗?
*
任务二:将 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 扩展包。
附:Laravel 从入门到精通系列之文件处理——ZIP 压缩与解压详解。
第一步:在 composer.json 的 require 列表中添加该软件包。
"chumper/zipper": "1.0.x"
第二步:在命令行终端执行更新命令。
composer update
第三步:在 app/config/app.php 配置文件中进行注册。
add to providers Chumper\Zipper\ZipperServiceProvider::class
add to aliases 'Zipper' => Chumper\Zipper\Zipper::class
第四步:编写代码遍历文件并将其打包至压缩包内。
$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();
第五步:演示如何读取和解压压缩包内的文件。
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 压缩文件并提供下载的完整实现方法,希望能对大家有所帮助。如有任何疑问,欢迎留言,小编会及时回复。在此也非常感谢大家对本站网站的支持!