Laravel 验证器和 excel 文件错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42089659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:17:26  来源:igfitidea点击:

Laravel validator and excel files error

phpexcellaravelvalidationcsv

提问by Exarkun

I have an input field who allaow peoples to upload files. I want that they can upload, word files like doc, and files like csv,xlsx.

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

When i try with a .doc no problem at all but when i try with an excel files, the validator fail and say that not the good extension.

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

Here you can see my code, the two lines of comments was an other solution i have try , and it don't work too :(.

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

Any help is welcome.

欢迎任何帮助。

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

回答by Exarkun

Ok, my fault. I had tried another solution, found on this website and it worked. Thanks for help Odin. It was my first question on this website. I am gonna see if I can help someone now. I post code for solution for someone in need :).

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

$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',
  ]
);

回答by Odin Thunder

Use "mimes" when you want to write an extentions (xlsx,doc,docx). In case when use mime-type like application/vnd.ms-excelyou must use validation rule mimetype

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

More mime types: more mime-types

更多 mime 类型: 更多 mime 类型

$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'
]

回答by stardust4891

Here's how I did it in Laravel 6 by checking the file extension.

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

Create a new validation rule:

创建新的验证规则:

php artisan make:rule ExcelRule

Here is the ExcelRule, which checks the file extension:

这是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.';
    }
}

As you can see, I'm checking for csv, xls, or xlsxhere. You can add any additional extensions you desire.

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

Using it in a controller:

在控制器中使用它:

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

回答by Prabakaran T

In Laravel you can use validate the file upload with extension using After Hooks. Read more from here!

在 Laravel 中,您可以使用After Hooks验证带有扩展名的文件上传。从这里阅读更多!

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

回答by Godson Mandla

I tried validators provided by laravel but all doesnt seems to work.. That gave me an idea to try to validate using normal php and it works like a cham

我尝试了 laravel 提供的验证器,但似乎都不起作用。

$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
}

回答by Maniruzzaman Akash

Firsttell that this is not the proper solution. But you can try this.

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

I've searched also for that and having so much trouble validating excel fileand their mimes type is not working for that unfortunately.

我也搜索过,但在验证时遇到了很多麻烦excel file,不幸的是,他们的 mime 类型对此不起作用。

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..!!');
   }
}

in namspace include must use File;

在 namspace 中包含 must use File;

You can validate any file by this way, Thanks.

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