Php 处理文件上载异常-Laravel

Php 处理文件上载异常-Laravel,php,laravel,exception,Php,Laravel,Exception,这是我上传文件到数据库的方式,但当上传的文件格式或类型无效时,我无法处理异常 我能够处理异常时,没有文件上传,但不是当文件类型无效或不符合标准 请问我该怎么做 控制器 public function import($id, Request $request) { $country= Country::all()->where('id',$id)->first(); if($request->file('imported-fi

这是我上传文件到数据库的方式,但当上传的文件格式或类型无效时,我无法处理异常

我能够处理异常时,没有文件上传,但不是当文件类型无效或不符合标准

请问我该怎么做

控制器

 public function import($id, Request $request)
    {


       $country= Country::all()->where('id',$id)->first();


           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);       
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }

我在我的一个项目中上传了excel文件。希望这能帮助您:-

$file = Input::file('imported-file');
Excel::load($file ,function($reader){
                    $reader->each(function($sheet){
                        YourMOdelName::firstOrCreate($sheet->toArray());
                    });
                });
YourModelName是您的表名,假设表是用户,那么您必须定义User。。。。。 通过这种方式,您可以获得上传文件的扩展名:-

$ext= Input::file('imported-file')->getClientOriginalExtension();
echo $ext; //print the extension here
希望对你有帮助

从中,您只能接受使用mime验证规则的特定类型的文件

        'file' => 'required | mimes:application/vnd.ms-excel', 

MIME类型<代码>应用程序/VND。MS Excel < /C> >将匹配这些文件扩展名:代码> XLS XLM XLA XLC XLT XLW < /代码>

< P>好,我通过检查LaaFLE文档很简单地解决了这一问题。这就是我刚才补充的内容

if(($request->file('imported-file')->getClientOriginalExtension() != 'xls, xlm, xla ,xlc, xlt, xlw'))
        {

        }    
else {

   //process the file

}

什么是无效类型?您上载的是哪一个文件?@SapneshNaik,我上载excel文件。所以当用户上传不同的格式时,我需要处理这个问题exception@kunal,我上传excel文件你在哪里做文件验证?你如何验证它是excel还是其他格式?你现在很好。。。我还向您提供了此解决方案(y)请参见我的答案@pogba