如果不是图像文件,Yii2 图像验证器会抛出错误
Yii2 Image validator throws an error if it is not image file
我有一个简单的图像文件输入验证器,如下所示:
public function rules()
{
return [
['thumbnail', 'image', 'minWidth' => 800],
];
}
但是如果我尝试发送一个 txt 文件,它不会显示错误消息,但是 ImageValidator
会抛出一个错误:
PHP Notice – yii\base\ErrorException
getimagesize(): Read error!
为什么会这样?为什么它不停止在图像规则上,如果它不是图像文件,为什么它会调用 getimagesize
?我怎样才能抑制它?
几次后我有了这个解决方法:
['thumbnail', 'image', 'minWidth' => 800, 'when' => function($model) {
$check = @getimagesize($model->thumbnail->tempName);
if( !$check ) $model->addError('thumbnail', 'File is not an image.');
if( !$check['mime'] || !in_array($check['mime'], ['image/jpg', 'image/jpeg']) ) $model->addError('thumbnail', 'File is not jpeg.');
return $check ? true : false;
}],
但正确的形式是
['thumbnail', 'image',
'extensions' => ['png', 'jpg', 'gif'],
'mimeTypes' => ['image/*'],
'minWidth' => 800],
我有一个简单的图像文件输入验证器,如下所示:
public function rules()
{
return [
['thumbnail', 'image', 'minWidth' => 800],
];
}
但是如果我尝试发送一个 txt 文件,它不会显示错误消息,但是 ImageValidator
会抛出一个错误:
PHP Notice – yii\base\ErrorException
getimagesize(): Read error!
为什么会这样?为什么它不停止在图像规则上,如果它不是图像文件,为什么它会调用 getimagesize
?我怎样才能抑制它?
几次后我有了这个解决方法:
['thumbnail', 'image', 'minWidth' => 800, 'when' => function($model) {
$check = @getimagesize($model->thumbnail->tempName);
if( !$check ) $model->addError('thumbnail', 'File is not an image.');
if( !$check['mime'] || !in_array($check['mime'], ['image/jpg', 'image/jpeg']) ) $model->addError('thumbnail', 'File is not jpeg.');
return $check ? true : false;
}],
但正确的形式是
['thumbnail', 'image',
'extensions' => ['png', 'jpg', 'gif'],
'mimeTypes' => ['image/*'],
'minWidth' => 800],