首页 > 解决方案 > 即使文件是图像,laravel 图像验证也始终有效

问题描述

我正在尝试将图像上传到我的数据库问题是当我使用验证器时,它总是返回 tru 显示错误即使我输入图像,头像文件也应该是图像,我尝试了 jpeg、pjg 和 png 但没有似乎工作

控制器

 public function store(Request $request)
    {

        $this -> validate($request ,[
            //other validators working fine
            'avatar' => ['nullable', 'image' ],


    ]);

    if($request->hasFile('avatar')){
        // Get filename with the extension
        $filenameWithExt = $request->file('avatar')->getClientOriginalName();
        // Get just filename
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        // Get just ext
        $extension = $request->file('avatar')->getClientOriginalExtension();
        // Filename to store
        $fileNameToStore= $filename.'_'.time().'.'.$extension;
        // Upload Image
        $path = $request->file('avatar')->storeAs('public/avatars', $fileNameToStore);
    } else {
        $fileNameToStore = 'noimage.jpg';
    }

         $member= new Member;
         //other inputs working fine
         $member->avatar = $fileNameToStore;

         $member->save(); 
    }

看法

<div class="form-group row">
    <label for="avatar" class="col-md-4 col-form-label text-md-right">image du membre</label>

   <div class="col-md-6">
       <input id="avatar" type="file" class=" @error('avatar') is-invalid @enderror" name="avatar"  autofocus>

   @error('avatar')
      <span class="invalid-feedback" role="alert">
          <strong>{{ $message }}</strong>
      </span>
   @enderror
 </div>

当我厌倦了删除验证器时它可以工作并且总是在数据库中获得 noimage

标签: phplaravellaravel-5eloquentlaravel-4

解决方案


您必须在表单中进行这样的更改

<form action="{{url('')}}/your_action" method="POST" id="" name="" enctype="multipart/form-data">

推荐阅读