CakePHP的文件上传验证器

时间:2011-01-29 11:30:56

标签: cakephp file-upload cakephp-1.3 validation

如何在CakePHP中为文件上传创建验证器?

1 个答案:

答案 0 :(得分:5)

var $validate = array(
        'imageupload' => array(
            'checksizeedit' => array(
                'rule' => array('checkSize',false),
                'message' => 'Invalid File size',
                'on' => 'update'
            ),
            'checktypeedit' =>array(
                'rule' => array('checkType',false),
                'message' => 'Invalid File type',
                'on' => 'update'
            ),
            'checkuploadedit' =>array(
                'rule' => array('checkUpload', false),
                'message' => 'Invalid file',
                'on' => 'update'
            ),
            'checksize' => array(
                'rule' => array('checkSize',true),
                'message' => 'Invalid File size',
                'on' => 'create'
            ),
            'checktype' =>array(
                'rule' => array('checkType',true),
                'message' => 'Invalid File type',
                'on' => 'create'
            ),
            'checkupload' =>array(
                'rule' => array('checkUpload', true),
                'message' => 'Invalid file',
                'on' => 'create'
            ),
        )
    );






function checkUpload($data, $required = false){
        $data = array_shift($data);
        if(!$required && $data['error'] == 4){
            return true;
        }
        //debug($data);
        if($required && $data['error'] !== 0){
            return false;
        }
        if($data['size'] == 0){
            return false;
        }
        return true;

        //if($required and $data)
    }

    function checkType($data, $required = false,$allowedMime = null){
        $data = array_shift($data);
        if(!$required && $data['error'] == 4){
            return true;
        }
        if(empty($allowedMime)){
            $allowedMime = array('image/gif','image/jpeg','image/pjpeg','image/png');
        }

        if(!in_array($data['type'], $allowedMime)){
            return false;
        }
        return true;
    }

    function checkSize($data, $required = false){
        $data = array_shift($data);
        if(!$required && $data['error'] == 4){
            return true;
        }
        if($data['size'] == 0||$data['size']/1024 > 2050){
            return false;
        }
        return true;
    }

您也可以参考this