上传可制定名称
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user