【问题标题】:Handling File Upload Exception - Laravel处理文件上传异常 - Laravel
【发布时间】:2017-12-06 09:45:26
【问题描述】:

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

我可以处理没有文件上传的异常,但不能处理文件类型无效或不符合标准的异常。

请问我该怎么做?

控制器

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

         }

        }

【问题讨论】:

  • 什么是无效类型?
  • 你上传的是哪个文件?
  • @SapneshNaik,我上传了 excel 文件。因此,当用户上传不同的格式时,我需要处理该异常
  • @kunal,我上传 excel 文件
  • 您在哪里进行文件验证?

标签: php laravel exception


【解决方案1】:

来自Laravel's documentation,您可以使用 mime 验证规则仅接受某种类型的文件,

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

mime 类型application/vnd.ms-excel 将匹配这些文件扩展名xls xlm xla xlc xlt xlw

【讨论】:

    【解决方案2】:

    我在我的一个项目中上传了 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
    

    希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      好的,我通过查看 laravel 文档以非常简单的方式解决了这个问题。这就是我刚刚添加的内容

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

      【讨论】:

      • 如何验证是excel还是其他格式?
      • 你现在很好......我也为你提供了这个解决方案(y)看我的回答@pogba
      猜你喜欢
      • 2014-01-25
      • 2014-04-22
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多