laravel 如何检查文件是否上传

How to check file is uploaded or not in laravel

我正在将图像文件上传到输入文件 ImageUpload。我需要检查文件是否已上传,然后创建一个唯一的文件名并将其保存在服务器上。

$file = $request->file('ImageUpload');
$filename=uniqid($user->id . '_'    ).".".$file->getClientOriginalExtension();
Storage::disk('public')->put($filename,File::get($file));

试试这个

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);
        }
}

试试这个。

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);                            
} 

您可以检查您的文件 variable 是否存在

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

但是,根据official documentation,要检查文件上传是否成功且没有任何错误,

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

Laravel 很广泛,它允许您保存文件而无需额外调用存储等

$filePath = $request->ImageUpload->storeAs('DIRECTORY_IN_STORAGE', 'CUSTOM_FILE_NAME'); // it return the path at which the file is now saved

我今天遇到了同样的问题,在官方 Laravel 文档上找到了这个解决方案。 顺便说一句,我正在使用Laravel 5.5。

if ($request->file('imageupload')!=null)
{
  return 'file uploaded';
}
else
{
  return 'file not uploaded';
}