文章转自:learnku.com/laravel/t/2…
更多文章:learnku.com/laravel/c/t…php
若是您须要您的用户支持多文件下载的话,最好的办法是建立一个压缩包并提供下载。看下在 Laravel 中的实现。laravel
事实上,这不是关于 Laravel 的,而是和 PHP 的关联更多,咱们准备使用从 PHP 5.2 以来就存在的 ZipArchive 类 ,若是要使用,须要确保php.ini 中的 ext-zip 扩展开启。bash
下面是代码展现:ui
$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);
复制代码
例子很简单,对吗?spa
Laravel 方面不须要有任何改变,咱们只须要添加一些简单的 PHP 代码来迭代这些文件。.net
$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 的扩展包来实现这个压缩方式。code
文章转自:learnku.com/laravel/t/2…
更多文章:learnku.com/laravel/c/t…cdn