How to check file is uploaded or not in laravel
Asked Answered
R

4

9

I am uploading an image file to the input file ImageUpload.I need to check if file has been uploaded then create a unique filename and save it on the server.

$file = $request->file('ImageUpload');
$filename=uniqid($user->id . '_'    ).".".$file->getClientOriginalExtension();
Storage::disk('public')->put($filename,File::get($file));
Remus answered 24/12, 2018 at 6:14 Comment(0)
M
33

You can check if your file variable exists as

if($request->hasFile('ImageUpload')){ }

But, as per official documentation, to check whether file upload is successful without any errors,

if($request('ImageUpload')->isValid()){ }

Laravel is extensive, it allows you to save file without writing extra call to Storage etc. as

$filePath = $request->ImageUpload->storeAs('DIRECTORY_IN_STORAGE', 'CUSTOM_FILE_NAME'); // it return the path at which the file is now saved
Marga answered 24/12, 2018 at 7:12 Comment(0)
N
7

Try this.

if($request->hasFile('ImageUpload'))
{
 $filenameWithExt    = $request->file('ImageUpload')->getClientOriginalName();
 $filename           = pathinfo($filenameWithExt, PATHINFO_FILENAME);
 $extension          = $request->file('ImageUpload')->getClientOriginalExtension();
 $fileNameToStore    = $filename.'_'.time().'.'.$extension;
 $path               = $request->file('ImageUpload')->storeAs('public', $fileNameToStore);                            
} 
Nonce answered 24/12, 2018 at 6:29 Comment(0)
H
6

try this one

if($request->hasFile('ImageUpload')) { //check file is getting or not..
        $file = $request->file('ImageUpload');
        $filename = uniqid($user->id . '_').".".$file->getClientOriginalExtension(); //create unique file name...
        Storage::disk('public')->put($filename,File::get($file));
        if(Storage::disk('public')->exists($filename)) {  // check file exists in directory or not
           info("file is store successfully : ".$filename);            
        }else { 
           info("file is not found : ".$filename);
        }
}
Horten answered 24/12, 2018 at 6:22 Comment(0)
W
1

I faced the same problem today and found this solution on official Laravel Docs. I am using Laravel 5.5 by the way.

if ($request->file('imageupload')!=null)
{
  return 'file uploaded';
}
else
{
  return 'file not uploaded';
}
Whitcomb answered 29/11, 2019 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.