Laravel validator and excel files error

后端 未结 7 1813
后悔当初
后悔当初 2020-12-09 12:31

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.

When i try with a .doc no proble

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 12:52

    In Laravel you can use validate the file upload with extension using After Hooks. Read more from 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;
    }
    

提交回复
热议问题