在项目中遇到文件上传的问题,这时候需要用到CFileValidator,但是官方的验证中少了一点点的处理,比如,对于图片,我只想上传尺寸正好是300x500的图片。怎么办?
所以我做了一点小小的扩展,于是我在rules里面加了这么两条:
PHP代码
- array('picname', 'application.validators.Myfile', 'on'=>'insert','types'=>'jpg,png','wrongType'=>'只允许上传jpg或者PNG','maxSize' => 1024*300,'tooLarge' => '图片最大只支持300K','imageSize'=>'768x1024','wrongImageSize'=>'对不起,图片尺寸只支持768*1024'),
- array('picname', 'application.validators.Myfile', 'on'=>'update','types'=>'jpg,png','wrongType'=>'只允许上传jpg或者PNG','maxSize' => 1024*300,'tooLarge' => '图片最大只支持300K','imageSize'=>'768x1024','wrongImageSize'=>'对不起,图片尺寸只支持768*1024','allowEmpty'=>true,),
数组的第二个字段就是一个全路径,告诉rules,对于picname用的是application.validators.Myfile类。这个类其实很简单,只是简单的扩展了官方的CFileValidator类,大致如下:
PHP代码
- class Myfile extends CFileValidator{
- public $imageSize;
- public $wrongImageSize;
- /**
- * @param CModel $object the object being validated
- * @param string $attribute the attribute being validated
- * @param CUploadedFile $file uploaded file passed to check against a set of rules
- * @return void
- */
- protected function validateFile($object, $attribute, $file){
- parent::validateFile($object,$attribute,$file);
- if($this->imageSize!=''&&strpos($this->imageSize,"x")!==false){
- list($width,$height) = @getimagesize($file->getTempName());
- $imageSize = sprintf("%sx%s",$width,$height);
- if($imageSize != $this->imageSize){
- $message=$this->wrongImageSize!==null?$this->wrongImageSize : Yii::t('yii','The file "{file}" cannot be uploaded. Only files with these size are allowed: {imagesize}.');
- $this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{extensions}'=>$this->imageSize));
- }
- }
- }
- }
我这种只是简单的判断是否与指定尺寸相符,如果需要检测小于指定范围的图片,那就需要多一点的判断了,也不会太难啦。主要是一个思路(感谢烂桔提供思路)