P粉1542284832023-08-01 00:11:46
If you wish to prevent the same file from being uploaded multiple times in different subdirectories, you can take advantage of Laravel's Filesystem and check whether the file exists before trying to upload it.
The File facade provides an exists method that you can use to check whether a file in a given path exists.
Here's how you might modify it:
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); } } } } }
The above code will only upload if the file does not exist in the specified directory. If the file already exists, an error response with the message 'File already exists' is returned.
One thing to note is the behavior of the getClientOriginalName() method. It will return the original name of the file from the client machine, which may cause problems if files from different clients have the same name. If this is a problem, consider implementing a unique naming convention when uploading.
Also, remember to import the necessary classes at the top of the file and take care to handle any potential issues such as missing required fields or failed database inserts.