From 88bc59ed87b94695ac30703a9a0b7df9923b4538 Mon Sep 17 00:00:00 2001 From: "WIN-C27C5MSVTPO\\16961" <1696136552@qq.com> Date: Mon, 15 Sep 2025 17:10:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E5=8F=AF=E5=88=B6=E5=AE=9A?= =?UTF-8?q?=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/common/service/UploadService.php | 35 ++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/app/common/service/UploadService.php b/app/common/service/UploadService.php index 33b9137..4204020 100644 --- a/app/common/service/UploadService.php +++ b/app/common/service/UploadService.php @@ -51,8 +51,39 @@ class UploadService $sceneUrl = $scene ? ($scene . '/') : ''; $dir = 'x_server/' . $sceneUrl . date('Ymd') . '/'; - $uniqueName = md5($originalName . microtime(true)); - $objectKey = $dir . $uniqueName . ($extension ? ('.' . $extension) : ''); + // 使用传入的 original_name 命名(缺少扩展名时补上推断的扩展名),并做简单安全处理 + $safeBaseName = preg_replace('/[\\\\\/]+/', '_', $originalName); + if ($extension && strtolower(pathinfo($safeBaseName, PATHINFO_EXTENSION)) !== strtolower($extension)) { + // 若提供的名称没有扩展名或扩展名不一致,则以推断扩展名为准 + $safeBaseName = pathinfo($safeBaseName, PATHINFO_FILENAME) . '.' . $extension; + } elseif (!$extension && !pathinfo($safeBaseName, PATHINFO_EXTENSION)) { + // 实在没有扩展名信息时,保持原名 + } + + // 重名检测:同一目录、同名且同类型则在文件名后追加序号 + $uploadedFilesService = new UploadedFilesService(); + $candidateName = $safeBaseName; + $nameBody = pathinfo($safeBaseName, PATHINFO_FILENAME); + $nameExt = pathinfo($safeBaseName, PATHINFO_EXTENSION); + $counter = 1; + while (true) { + $candidatePath = $dir . $candidateName; + $existing = $uploadedFilesService->getFile(['file_path' => $candidatePath]); + if (!$existing) { + break; + } + // 若存在同路径同名,且类型也相同,则追加序号 + if (isset($existing->file_type) && strtolower($existing->file_type) === strtolower($mime)) { + $suffix = ' (' . $counter . ')'; + $candidateName = $nameBody . $suffix . ($nameExt !== '' ? ('.' . $nameExt) : ''); + $counter++; + continue; + } + // 类型不同则允许同名,结束循环 + break; + } + + $objectKey = $dir . $candidateName; $ossService = new OssService(); $ossService->uploadImage($filePath, $objectKey);