I created a add view where multiple files can be upload at same time :
View
The file path when file will be uploaded is like – Drawings/PartNumber/Type/filename.extension
How can I check in Drawing Folder any file cant not be same with extension like
- Drawings/PartNumber1/Type1/filename1.pdf
- Drawings/PartNumber2/Type2/filename1.pdf
- Drawings/PartNumber1/Type3/filename1.pdf
- Drawings/PartNumber1/filename1.pdf
- Drawings/filename1.pdf
never will be accepted.
My function is :
public function AddNewPart(Request $request)
{
if (array_key_exists('DrawingFile',$data)) {
foreach($request->file('DrawingFile') as $key=>$file)
{
if ($data['fileupload_ID'][$key]==NULL) {
$extension=$file->getClientOriginalExtension();
$file_name2 = $file->getClientOriginalName();
$filepath='Drawings/'.$data['PartNumber'].'/'.$data['Type'][$key].'/'.$file_name2;
$file->move(public_path('Drawings/'.$data['PartNumber'].'/'.$data['Type'][$key].'/'), $file_name2);
$DocumentData2=array('Type'=>$data['Type'][$key],'fcontent'=>$file_name2,'condpartno'=>$data['PartNumber'],'fname'=>$filepath,
'DrawingNo'=>$data['DrawingNo'][$key],'DocumentType'=>$data['Type'][$key]);
DB::table('fileupload')->insert($DocumentData2);
}
}
}
}
2
Answers
I got the solution
If you desire to prevent the identical file being uploaded multiple times across diverse subdirectories, you could leverage Laravel’s Filesystem and check whether the file exists prior to attempting to upload it.
The
File
facade provides anexists
method that you can employ to check if a file exists within a given path.Here’s how you might modify your method:
The above code will only upload the file if it doesn’t already exist within the specified directory. If it does exist, it will return an error response with the message ‘File already exists.’.
One thing to bear in mind is the behavior of
getClientOriginalName()
. It will return the original name of the file as from the client’s machine, which could cause problems if files from different clients have the same name. Consider implementing a unique naming convention for files upon upload if this is a concern.Also, remember to import the necessary classes at the top of your file and take care to handle all potential issues, such as missing required fields or failed database inserts.