function zip_file($packingFile, $zipDir, $zipFile = null)
{
if (!file_exists($zipDir)) {
mkdir($zipDir, 0777, true);
}
$zipFile = $zipFile ?: md5(date('ymdhis')) . '.zip';
$zip = new \ZipArchive();
fopen($zipDir . $zipFile, "w");
if ($zip->open($zipDir . $zipFile, \ZipArchive::OVERWRITE) === TRUE) {
if (is_array($packingFile)) {
foreach ($packingFile as $file) {
if (isset($file['path']) && !empty($file['path'])) {
$path = strpos($file['path'], 'http') !== false ? public_path(substr($file['path'], strpos($file['path'], '/', strpos($file['path'], '//') + 2))) : public_path($file['path']);
$zip->addFile($path, isset($file['packing_name']) && !empty($file['packing_name']) ? '/' . $file['packing_name'] . '.' . pathinfo($path, PATHINFO_EXTENSION) : null);
}
}
} else {
$zip->addFile($packingFile);
}
}
$zip->close(); //关闭处理的zip文件
}
public function download($data)
{
$packingFile = Drawing::where('id', $data['drawing_id'])->get([DB::raw($data['type'] . '_img as path'), DB::raw('code as packing_name')]);
if (!$packingFile->count()) {
return $this->formatReturn(null, 400, '未找到图档图片');
}
$packingFile = $packingFile->toArray();
if (empty(array_filter(array_column($packingFile, 'path')))) {
return $this->formatReturn(null, 400, '未找到对应类型的图片');
}
$zipPath = '/zip/';
$zipName = date('ymdhis') . '-图档.zip';
zip_file($packingFile, public_path($zipPath), $zipName);
if (!file_exists(public_path($zipPath . $zipName))) {
return $this->formatReturn(null, 400, '下载失败');
}
return $this->formatReturn(['url' => $zipPath . $zipName]);
}