本篇文章给大家带来的内容是关于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中文网其他相关文章!