即使文件是图像,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

您也可以这样做:

$this -> validate($request ,[
//other validators working fine
]);
if($request->hasFile('avatar')){
$this -> validate($request ,[
'avatar' => 'image',
]);
}

首先 u 验证表单,然后,如果文件存在,则验证图像。

你必须在表单中这样改变

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

最新更新