需求描述:
? ?根据记录类型对图片实现分包处理并以压缩包形式实现下载
示例代码:
? ??
public static function downloadZip($files,$fileName = 'time'){
if (!is_array($files)){
return false;
}
set_time_limit(1200);
$zip_name = "示例";
$zip = new \ZipArchive();
if ($zip->open($zip_name, \ZipArchive::CREATE) !== TRUE) {
exit ('无法打开文件,或者文件创建失败');
}
$folders = [];
foreach($files as $key => $file){
//判断结转单类型进行分包存储 1: VIP签收单 2:整体结课单 3:排版确认单
$dir = './over-images';
if(!file_exists($dir)){
mkdir($dir);
}
if($file["type"] == 1){
$dir = './over-images/Vip';
}
if($file["type"] == 2){
$dir = './over-images/EndClass';
}
if($file["type"] == 3){
$dir = './over-images/TypeConfirm';
}
//类型文件夹不存在,创建
if(!file_exists($dir)){
mkdir($dir);
}
//存储文件到临时文件夹
$file_remote_url = self::getImg($file['url']);
$fileContent = file_get_contents($file_remote_url);
$file_name = iconv('utf-8', 'GBK', basename($file['url']));
//处理文件名:加标识(分包后不知图片对应哪条数据)
$file_name_array = explode('.',$file_name);
$file_front = $file['num'];
$file_name = $file_front.'.'.$file_name_array[1];
file_put_contents($dir.'/'.$file_name,$fileContent);
$folders[] = [
'name'=>$file_name,
'src' =>$dir.'/'.$file_name,
'id' =>$key+1,
'type'=>$file['type'],//分组依据不能丢
];
}
// 图片的路径,可以是多个文件
$object = $zip->open($zip_name, \ZipArchive::CREATE);//创建zip压缩对象
if($object){
foreach ($folders as $folder) {
$zip_dir = "VIP签收单/";
if($folder['type'] == 1){
$zip_dir = "VIP签收单/";
}
if($folder['type'] == 2){
$zip_dir = "整体结课单/";
}
if($folder['type'] == 3){
$zip_dir = "排版确认单/";
}
$zip->addFile($folder["src"],$zip_dir.$folder['name']);//文件存入对应文件夹
}
}
$zip->close();
//清空(擦除)缓冲区并关闭输出缓冲
ob_end_clean();
header('Content-Type: application/zip;charset=utf8');
//下载建好的.zip压缩包
header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
header("Content-Type: application/force-download");//告诉浏览器强制下载
header("Content-Transfer-Encoding: binary");//声明一个下载的文件
header('Content-Type: application/zip');//设置文件内容类型为zip
header('Content-Disposition: attachment; filename='.$fileName.'.zip');//声明文件名
header('Content-Length: ' . filesize($zip_name));//声明文件大小
readfile($zip_name);
unlink($zip_name);
//干掉临时文件,防止空间占用
$parent_dir = ["./over-images/Vip/","./over-images/EndClass/","./over-images/TypeConfirm/"];
foreach($parent_dir as $dir){
if(file_exists($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file!='.' && $file!='..') {
unlink($dir.'/'.$file);
}
}
}
closedir($dh);
}
}
die;
}
功能效果:
?
?
?
?
|