【问题标题】:Laravel validator and excel files errorLaravel 验证器和 excel 文件错误
【发布时间】:2017-06-24 16:27:49
【问题描述】:

我有一个允许人们上传文件的输入字段。 我希望他们可以上传,像 doc 这样的 word 文件,以及像 csv、xlsx 这样的文件。

当我尝试使用 .doc 时完全没有问题,但是当我尝试使用 excel 文件时,验证器失败并说这不是好的扩展名。

在这里你可以看到我的代码,两行 cmets 是我尝试过的另一个解决方案,但它也不起作用:(。

欢迎任何帮助。

public function postFile(Request $request)
{ //Règle de validation avec les type de fichiers acceptés

 if(isset($request->file)){
//dd($request);
   $validator=Validator::make($request->all(),[
     'file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp,application/csv,application/excel,
      application/vnd.ms-excel, application/vnd.msexcel,
      text/csv, text/anytext, text/plain, text/x-c,
      text/comma-separated-values,
      inode/x-empty,
      application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  /*  'extension'  => strtolower($request->file->getClientOriginalExtension()),
     'extension'=>'required|in:doc,csv,xlsx,xls,docx,ppt,odt,ods,odp'*/
   ]);
  if ($validator->fails()) {
     return back()
                ->withErrors($validator);
   }

【问题讨论】:

  • 请注意,文件不是空的,我在尝试使用空文件时浪费了 4 个小时

标签: php excel laravel validation csv


【解决方案1】:

好吧,我的错。 我尝试了另一种解决方案,在这个网站上找到并且它有效。 感谢奥丁的帮助。 这是我在这个网站上的第一个问题。我现在要看看我能不能帮助别人。 我为有需要的人发布了解决方案的代码:)。

$validator = Validator::make(
  [
      'file'      => $request->file,
      'extension' => strtolower($request->file->getClientOriginalExtension()),
  ],
  [
      'file'          => 'required',
      'extension'      => 'required|in:doc,csv,xlsx,xls,docx,ppt,odt,ods,odp',
  ]
);

【讨论】:

    【解决方案2】:

    当你想写扩展时使用“mimes”(xlsx,doc,docx)。 如果使用像 application/vnd.ms-excel 这样的 mime 类型,则必须使用验证规则 mimetype

    更多 mime 类型:more mime-types

    $validator=Validator::make($request->all(),[
     //use this
        'file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp'
     //or this
        'file'=>'required|max:50000|mimetypes:application/csv,application/excel,
            application/vnd.ms-excel, application/vnd.msexcel,
            text/csv, text/anytext, text/plain, text/x-c,
            text/comma-separated-values,
            inode/x-empty,
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ]);
    

    【讨论】:

    • 感谢您的回答,但我已经尝试过这两种解决方案;和它是一回事。当我尝试上传 .xlsx 或 .csv 时,验证器失败。
    • 这个解决方案对我有用。 .xls、.xlsx、.ods 文件的良好验证(通过 mimetypes)。然而,一个例外。它无法验证使用 libreoffice 制作的 .xls 和 .xlsx 文件。
    【解决方案3】:

    这是我在 Laravel 6 中通过检查文件扩展名的方法。

    创建新的验证规则:

    php artisan make:rule ExcelRule
    

    这里是ExcelRule,它检查文件扩展名:

    namespace App\Rules;
    
    use Illuminate\Contracts\Validation\Rule;
    use Illuminate\Http\UploadedFile;
    
    class ExcelRule implements Rule
    {
        private $file;
    
        public function __construct(UploadedFile $file)
        {
            $this->file = $file;
        }
    
        public function passes($attribute, $value)
        {
            $extension = strtolower($this->file->getClientOriginalExtension());
    
            return in_array($extension, ['csv', 'xls', 'xlsx']);
        }
    
        public function message()
        {
            return 'The excel file must be a file of type: csv, xls, xlsx.';
        }
    }
    

    如您所见,我在这里检查csvxlsxlsx。您可以添加所需的任何其他扩展。

    在控制器中使用它:

    public function uploadExcelFile(Request $request)
    {
        $request->validate([
            'excel_file' => ['required', new ExcelRule($request->file('excel_file'))],
        ]);
    
        $model->update([
            'excel_file' => $request->file('excel_file')->store('excel_files'),
        ]);
    
        return redirect()->route('my_route_name')->with('Excel file uploaded!');
    }
    

    【讨论】:

      【解决方案4】:

      首先说明这不是正确的解决方案。不过你可以试试这个。

      我也对此进行了搜索,但在验证 excel file 时遇到了很多麻烦,不幸的是,他们的 mimes 类型无法正常工作。

      if($request->hasFile('file'))
      {
         $extension = File::extension($request->file->getClientOriginalName());
         if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {
            //'Your file is a valid xls or csv file'
         }else {
            //'File is a '.$extension.' file.!! Please upload a valid xls/csv file..!!');
         }
      }
      

      在 namspace 中必须包含 use File;

      您可以通过这种方式验证任何文件,谢谢。

      【讨论】:

      • 我找到了一个解决方案,你可以看到最后一个答案,它的工作:)
      【解决方案5】:

      在 Laravel 中,您可以使用 After Hooks 验证文件上传的扩展名。阅读更多来自here

      $validator->after(function ($validator) use ($request){
          if($this->checkExcelFile($request->file('file')->getClientOriginalExtension()) == false) {
              //return validator with error by file input name
              $validator->errors()->add('file', 'The file must be a file of type: csv, xlsx, xls');
          }
      });
      
      function checkExcelFile($file_ext){
          $valid=array(
              'csv','xls','xlsx' // add your extensions here.
          );        
          return in_array($file_ext,$valid) ? true : false;
      }
      

      【讨论】:

        【解决方案6】:

        我尝试了 laravel 提供的验证器,但似乎都不起作用。这给了我一个尝试使用普通 php 进行验证的想法,它就像一个 cham 一样工作

        $extensions = array("xls","xlsx","xlm","xla","xlc","xlt","xlw");
        
                $result = array($request->file('import_file')->getClientOriginalExtension());
        
        if(in_array($result[0],$extensions)){
        // Do something when Succeeded 
        }else{
         // Do something when it fails
        }
        

        【讨论】:

          【解决方案7】:

          就是这样!我自己试过,如果你只测试mimes:csv,当文件名有空格时它会失败。

          我通过验证所做的是使用required|mimes:csv,txt

          但正如您已经建议的那样,您需要进行一些手动验证。

          前端验证在用户体验方面是一件好事,但您永远不能只相信在与您的服务器不同的机器上运行的验证。如果您要进行任何 javascript 验证,请始终在服务器中再次验证它。

          在你的情况下,因为它是一个不寻常的文件名的例外,而不是错误的格式,我会使用 mimes:csv,txt 放宽 mime 类型验证,然后使用一个包来解析 CSV 文件,通常是这个包当格式无效时引发异常。

          处理 CSV 的两个很棒的包是:

          [https://github.com/Maatwebsite/Laravel-Excel] [http://csv.thephpleague.com/] 希望对您有所帮助。

          [https://laracasts.com/discuss/channels/general-discussion/csv-file-upload-request-validation]

          【讨论】:

            【解决方案8】:

            简单的解决方案是使用 mime

             $request->validate([
                'file'=> 'required|mimes:xlsx, csv, xls'
             ]);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-05-20
              • 2018-05-22
              • 2018-09-05
              • 2013-10-31
              • 1970-01-01
              相关资源
              最近更新 更多