PHP上傳文件仿微信文件名命名
- 2019 年 12 月 16 日
- 筆記
在做文件上傳時遇到一個需求,上傳時判斷文件名稱是否重複,如果重複則在後面標記數字,重新命名後繼續上傳。
比如文件名為「測試.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 ); } 

