Laravel 中创建 Zip 压缩文件并提供下载

1,847 阅读1分钟

文章转自:learnku.com/laravel/t/2…
更多文章:learnku.com/laravel/c/t…

如果您需要您的用户支持多文件下载的话,最好的办法是创建一个压缩包并提供下载。看下在 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 的扩展包来实现这个压缩方式。

文章转自:learnku.com/laravel/t/2…
更多文章:learnku.com/laravel/c/t…