在做文件上传时遇到一个需求,上传时判断文件名称是否重复,如果重复则在后面标记数字,重新命名后继续上传。
比如文件名为“测试.jpg”,上传时假如该文件存在,则改名为“测试(1).jpg”上传。
下面为代码展示
效果图
public function uploadFile(Request $request) { // $data = json_decode(file_get_contents("php://input"), true); $userId = request()->userid; if (!$userId) return $this->responseJson(self::CODE_USER_NOT_EXIST, trans(‘api.user.notExist‘)); $file = $request->file(‘file‘); Log::channel(‘notify‘)->info($file); //获取文件名 $fileName = $file->getClientOriginalName(); $fileSize = $file->getClientSize(); $fileType = $file->guessClientExtension(); $path = ‘upload\\‘ . $userId . ‘\\‘; //判断文件是否存在 $exists = Storage::disk(‘public‘)->exists($path . $fileName); if ($exists) { //存在,改名 $houzhui = ‘.‘ . substr(strrchr($fileName, ‘.‘), 1); $result = substr($fileName, 0, ‘-‘ . strlen($houzhui)); for ($i = 1; $i < 1000; $i++) { $saveName = iconv("utf-8", "gb2312", $result . ‘(‘ . $i . ‘)‘ . $houzhui); $exists = Storage::disk(‘public‘)->exists($path . $saveName); if (!$exists) { $fileName = $result . ‘(‘ . $i . ‘)‘ . $houzhui; $name = $result . ‘(‘ . $i . ‘)‘ . $houzhui; break; } } } $upload = $request->file(‘file‘)->storeAs( ‘public‘, $path . $fileName ); }