如果您希望防止相同的文件在不同的子目錄中被多次上傳,您可以利用 Laravel 的文件系統(tǒng)(Filesystem)并在嘗試上傳文件之前檢查文件是否存在。
文件門面(File facade)提供了一個 exists 方法,您可以使用它來檢查給定路徑中的文件是否存在。
下面是您可能會修改的方法:
use Illuminate\Support\Facades\File; public function AddNewPart(Request $request) { if (array_key_exists('DrawingFile',$request->all())) { foreach($request->file('DrawingFile') as $key=>$file) { if ($request->fileupload_ID[$key] == NULL) { $extension = $file->getClientOriginalExtension(); $file_name2 = $file->getClientOriginalName(); $filepath = 'Drawings/'.$request->PartNumber.'/'.$request->Type[$key].'/'.$file_name2; // Check if the file already exists before moving it if (!File::exists(public_path($filepath))) { $file->move(public_path('Drawings/'.$request->PartNumber.'/'.$request->Type[$key].'/'), $file_name2); $DocumentData2 = array( 'Type'=>$request->Type[$key], 'fcontent'=>$file_name2, 'condpartno'=>$request->PartNumber, 'fname'=>$filepath, 'DrawingNo'=>$request->DrawingNo[$key], 'DocumentType'=>$request->Type[$key] ); DB::table('fileupload')->insert($DocumentData2); } else { // You might want to return some feedback to the user here return response()->json([ 'error' => 'File already exists.' ], 400); } } } } }
上述代碼只會在指定目錄中不存在該文件時才進行上傳。如果文件已經(jīng)存在,則會返回一個帶有消息 '文件已存在' 的錯誤響應。
需要注意的一點是 getClientOriginalName() 方法的行為。它將返回來自客戶端機器的文件的原始名稱,如果來自不同客戶端的文件具有相同的名稱,可能會導致問題。如果這是一個問題,請考慮在上傳時實施唯一命名約定。
此外,請記住在文件的頂部導入必要的類,并注意處理所有潛在問題,如缺少必填字段或數(shù)據(jù)庫插入失敗。