Laravel 中建立 Zip 壓縮檔案並提供下載
文章轉自: https://learnku.com/laravel/t...
更多文章: https://learnku.com/laravel/c...
如果您需要您的使用者支援多檔案下載的話,最好的辦法是建立一個壓縮包並提供下載。看下在 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 的擴充套件包來實現這個壓縮方式。