本篇文章給大家?guī)淼膬?nèi)容是關(guān)于laravel中創(chuàng)建Zip壓縮文件并提供下載的代碼示例,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
如果您需要您的用戶支持多文件下載的話,最好的辦法是創(chuàng)建一個壓縮包并提供下載。看下在 Laravel 中的實現(xiàn)。
事實上,這不是關(guān)于 Laravel 的,而是和 php 的關(guān)聯(lián)更多,我們準備使用從 PHP 5.2 以來就存在的?ZipArchive 類?,如果要使用,需要確保php.ini 中的 ext-zip 擴展開啟。
任務(wù) 1:?存儲用戶的發(fā)票文件到?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'; // 添加文件:第二個參數(shù)是待壓縮文件在壓縮包中的路徑 // 所以,它將在 ZIP 中創(chuàng)建另一個名為 "storage/" 的路徑,并把文件放入目錄。 $zip->addFile(storage_path($invoice_file), $invoice_file); $zip->close(); // 我們將會在文件下載后立刻把文件返回原樣 return response()->download($zip_file);
例子很簡單,對嗎?
任務(wù) 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 的擴展包來實現(xiàn)這個壓縮方式。
【相關(guān)推薦:PHP視頻教程】
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END