1
如何在CakePHP中爲文件上傳創建驗證器?CakePHP的文件上傳驗證器
如何在CakePHP中爲文件上傳創建驗證器?CakePHP的文件上傳驗證器
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
tnx,它有幫助。但是,如果驗證失敗,爲什麼我不能得到錯誤消息? – user198003 2011-02-01 18:17:06
你到底要驗證什麼? – Leo 2011-01-30 10:52:46