当前位置: 首页 > 后端技术 > PHP

Laravel 中创建 Zip 压缩文件并提供下载

时间:2023-03-29 14:39:00 PHP

在Laravel中创建一个Zip压缩文件并提供下载如果您的用户支持多个文件下载,最好的方法是创建一个zip文件并提供下载。看一下Laravel中的实现。其实这不是关于Laravel,更多的是关于PHP,我们将使用自PHP5.2以来存在的ZipArchive类,如果要使用它,需要确保在php中启用了ext-zip扩展。ini.任务一:将用户的发票文件存储到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中的路径//因此,它会在ZIP中创建另一个名为“storage/”的路径,并将文件放入目录中.$zip->addFile(storage_path($invoice_file),$invoice_file);$zip->close();//我们将在文件下载后立即返回文件returnresponse()->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($filesas$name=>$file){//我们想跳过所有子目录if(!$file->isDir()){$文件路径=$文件->getRealPath();//使用substr/strlen获取文件扩展名$relativePath='invoices/'.substr($filePath,strlen($path)+1);$zip->addFile($filePath,$relativePath);}}$zip->close();returnresponse()->download($zip_file);这基本上是在这里完成的。你看,你不需要任何Laravel扩展来实现这种压缩。文章转自:https://learnku.com/laravel/t...更多文章:https://learnku.com/laravel/c...