這篇文章帶給大家的內容是關於Laravel中創建Zip壓縮檔並提供下載的程式碼範例,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
如果您需要您的用戶支援多檔案下載的話,最好的方法是建立壓縮包並提供下載。看下在 Laravel 中的實作。
事實上,這不是關於Laravel 的,而是和PHP 的關聯更多,我們準備使用從PHP 5.2 以來就存在的 ZipArchive 類別 ,如果要使用,需要確保php.ini 中的ext-zip 擴充功能開啟。
任務 1: 儲存使用者的發票檔案到 storage/invoices/aaa001.pdf
以下是程式碼展示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $zip_file = 'invoices.zip' ;
$zip = new \ZipArchive();
$zip ->open( $zip_file , \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$invoice_file = 'invoices/aaa001.pdf' ;
$zip ->addFile(storage_path( $invoice_file ), $invoice_file );
$zip ->close();
return response()->download( $zip_file );
|
登入後複製
範例很簡單,對嗎?
任務 2: 壓縮 全部 檔案到 storage/invoices 目錄中
Laravel 方面不需要有任何改變,我們只需要加入一些簡單的 PHP 程式碼來迭代這些檔案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $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();
$relativePath = 'invoices/' . substr ( $filePath , strlen ( $path ) + 1);
$zip ->addFile( $filePath , $relativePath );
}
}
$zip ->close();
return response()->download( $zip_file );
|
登入後複製
到這裡基本上就算完成了。你看,你不需要任何 Laravel 的擴充包來實現這個壓縮方式。
【相關推薦:PHP影片教學】
#
以上是Laravel中建立Zip壓縮檔案並提供下載的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!