Using Mimes for Validating Laravel File Post - Word File

匆匆过客 提交于 2020-06-27 16:19:12

问题


I have a form that I post file. I am trying to use validation to accept only word documents. I tried using mime types however doesn't seem to work and I couldn't spot my mistake.

<form action="" method="post">
   <div class="form-group{{ $errors->has('myFile') ? ' has-error' : '' }}">
      <div class="col-xs-12">
           <div class="form-material">
               <input class="form-control" type="file" id="myFile" name="myFile">
               <label for="myFile">MyFile</label>
               @if ($errors->has('myFile'))
                    <div {{ $errors->first('myFile') }}</div>
               @endif
           </div>
      </div>
   </div>
</form>

This posts successfully and I receive it in my controller.

In my controller, I try to validate it, however it is always returning the error, even though the file is in '.doc' format.

public function myController(Request $request) {
     $validator = MyValidations::myFormValidator($request->all());

     if ($validator->fails()) {
          $this->throwValidationException(
               $request, $validator
          );
     }

     ...
}

and the validator:

public static function myFormValidator($data) {
    return Validator::make($data, [
        'myFile' => 'required|mimes:application/msword'

        // I also tried
        // 'myFile' => 'required|mimes:doc,docx'
    ]);
}

Edit: I have seen some posts on SO, regarding that there is a file config > mimes.php but I don't have it on Laravel 5.3


回答1:


Actually, there is nothing really wrong with your validation code. The problem is that your form is not submitting the files properly.

Add the proper enctype to your form like so:

<form action="" method="post" enctype="multipart/form-data">

Also make sure to get the syntax right for validation (but I think you knew this part). Use either of these two:

'myFile' => 'required|mimes:doc,docx'
'myFile' => 'required|mimetypes:application/msword'



回答2:


Try this:

'myFile': 'required|mimes:doc,docx'


来源:https://stackoverflow.com/questions/40638580/using-mimes-for-validating-laravel-file-post-word-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!