The content of this article is about creating Zip compressed files in Laravel and providing code examples for downloading. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.
If you need your users to support multiple file downloads, the best way is to create a compressed package and provide it for download. Take a look at the implementation in Laravel.
In fact, this is not about Laravel, but more related to PHP. We are going to use the ZipArchive class that has existed since PHP 5.2. If you want to use it, you need to make surephp.ini# The ext-zip extension in ## is enabled.
Task 1: Store the user's invoice file to storage/invoices/aaa001.pdfThe following is the code display:$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);
$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);
PHP video tutorial】
The above is the detailed content of Create Zip compressed files in Laravel and provide downloadable code examples. For more information, please follow other related articles on the PHP Chinese website!