laravel:生成zip压缩包并下载(10.27.0)
一,php代码:
1,封装类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?php namespace App\extend\zip; class Zip { //打包一个zip文件 public function makeZip( $pathArr , $zipName ) { $zip = new \ZipArchive(); if ( $zip ->open( $zipName ,\ZipArchive::CREATE|\ZipArchive::OVERWRITE)){ foreach ( $pathArr as $file ){ if (! file_exists ( $file )){ continue ; } //向压缩包中添加文件 $zip ->addFile( $file , basename ( $file )); } $zip ->close(); return [ 'code' =>0, 'msg' => "创建成功" , 'path' => $zipName ]; } else { return [ 'code' =>1, 'msg' => '创建失败' ]; } } } |
2,controller中调用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/* *生成并下载zip包 */ public function downzip(Request $request ){ //包中文件列表 $pathArr = [ "/var/www/html/goodsImage/orig/61e7c322b748b.gif" , "/var/www/html/goodsImage/orig/gsl.jpeg" , ]; //压缩包的文件名 $dateRand = date ( "YmdHis" ). "_" .rand(1000,9999); $zipName = "/var/www/html/goodsImage/image_" . $dateRand . ".zip" ; //生成压缩包 $zip = new Zip(); $res = $zip ->makeZip( $pathArr , $zipName ); //下载 return response()->download( $zipName ); } |
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/01/laravel-sheng-cheng-zip-ya-suo-bao-bing-xia-zai-10-27/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果:
三,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0