thinkphp6: 生成zip压缩包并下载(php 8.1.1 / thinkphp v6.0.10LTS )
一,编写php代码
1,lib/util/zip.php
<?php namespace app\lib\util; 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中调用
<?php declare (strict_types = 1); namespace app\controller; controller/Article.php use app\lib\util\zip; class Article extends BaseController { //生成zip文件 public function zip() { $pathArr = [ "/var/www/html/goodsimage/orig/61e386409e626.jpg", "/var/www/html/goodsimage/orig/61e38640dca86.jpg", ]; $zipName = "/var/www/html/goodsimage/image.zip"; $zip = new zip(); $res =$zip->makeZip($pathArr,$zipName); //if ($res['code']) echo $res['code']; exit; } //下载zip文件 public function downZip() { $zipName = "/var/www/html/goodsimage/image.zip"; return download($zipName,"image.zip"); } }
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/29/thinkphp6-sheng-cheng-zip-ya-suo-bao-bing-xia-zai-php-8-1-1/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果
1,生成zip:
查看图片:
访问url:
http://192.168.219.6:8000/article/zip
返回:
查看生成的压缩包:
注意:保存生成的zip包文件的路径需要有写入权限
2,下载zip包:
访问:
http://192.168.219.6:8000/article/downzip
返回:
三,查看php和thinkphp的版本:
php:
liuhongdi@lhdpc:/data/php/admapi$ php --version PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.1, Copyright (c) Zend Technologies with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies
thinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/ liuhongdi@lhdpc:/data/php/admapi$ php think version v6.0.10LTS