Laravel 中建立 Zip 壓縮文件並提供下載

圖片

文章轉自: https://learnku.com/laravel/t...

更多文章: https://learnku.com/laravel/c...

若是您須要您的用戶支持多文件下載的話,最好的辦法是建立一個壓縮包並提供下載。看下在 Laravel 中的實現。php

事實上,這不是關於 Laravel 的,而是和 PHP 的關聯更多,咱們準備使用從 PHP 5.2 以來就存在的 ZipArchive 類 ,若是要使用,須要確保php.ini 中的 ext-zip 擴展開啓。laravel

任務 1: 存儲用戶的發票文件到 storage/invoices/aaa001.pdf

下面是代碼展現:spa

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

例子很簡單,對嗎?.net

        • *

任務 2: 壓縮 所有 文件到 storage/invoices 目錄中

Laravel 方面不須要有任何改變,咱們只須要添加一些簡單的 PHP 代碼來迭代這些文件。code

$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 的擴展包來實現這個壓縮方式。圖片

文章轉自: https://learnku.com/laravel/t...

更多文章: https://learnku.com/laravel/c...
相關文章
相關標籤/搜索