Laravel 中创建 Zip 压缩文件并提供下载的实现方法
如果您需要您的用户支持多文件下载的话,最好的办法是创建一个压缩包并提供下载。下面通过本文给大家看下在Laravel中的实现。
事实上,这不是关于Laravel的,而是和PHP的关联更多,我们准备使用从PHP5.2以来就存在的ZipArchive类,如果要使用,需要确保php.ini中的ext-zip扩展开启。
任务1:存储用户的发票文件到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中创建另一个名为"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()){
$filePath=$file->getRealPath();
//用substr/strlen获取文件扩展名
$relativePath='invoices/'.substr($filePath,strlen($path)+1);
$zip->addFile($filePath,$relativePath);
}
}
$zip->close();
returnresponse()->download($zip_file);
到这里基本就算完成了。你看,你不需要任何Laravel的扩展包来实现这个压缩方式。
PS:下面看下laravel从入门到精通之文件处理压缩/解压zip
1:将此软件包添加到所需软件包列表中composer.json
"chumper/zipper":"1.0.x"
2:命令行执行
composerupdate
3:配置app/config/app.php
addtoprovidersChumper\Zipper\ZipperServiceProvider::class addtoaliases'Zipper'=>Chumper\Zipper\Zipper::class
4:遍历文件打包至压缩包
$files=Array();
foreach($studentas$key=>$data){
if($data->photopath!=null){
$check=glob(storage_path('photo/'.$data->photopath));
$files=array_merge($files,$check);
}
}
Zipper::make(storage_path().'/systemImg/'.$name)->add($files)->close();
5:读取压缩包文件
Zipper::make(storage_path().'/photo/photos')->extractTo(storage_path('temp'));
$zip=new\ZipArchive();//方法2:流处理,新建一个ZipArchive的对象
$logFiles=Zipper::make($path)->listFiles('/\.png$/i');
if($zip->open($path)===TRUE){
foreach($logFilesas$key){
$stream=$zip->getStream($key);
$str=stream_get_contents($stream);//这里注意获取到的文本编码
$name=iconv("utf-8","gb2312//IGNORE",$key);
file_put_contents(storage_path().'\temp\\'.$name,$str);
}
}else{
return'{"statusCode":"300","message":"上传失败,请检查照片"}';
}
总结
以上所述是小编给大家介绍的Laravel中创建Zip压缩文件并提供下载的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!