CakePHP 2.x:我很努力验证表单中的图像上传字段以添加用户。上传字段不是强制性的。但它在图像上传时始终将该字段验证为false。似乎整个验证工作部分工作。任何帮助,将不胜感激CakePHP:如果文件不存在,表单上传字段的验证
user.php的模型:
public $validate = array(
'picture' => array(
'required' => false,
'allowEmpty' => true,
'custom' => array(
'rule' => array('imageExist'),
'message' => 'There is already a picture with that name on the server'
)
));
// function to check if file already exists
public function imageExist($check) {
$picturename = $check['picture'];
$path = WWW_ROOT . 'userimages/';
$file = $path . $picturename;
if (file_exists($file)) {
return false;
} else {
return true;
}
}
add.ctp:
<?php
echo $this->Form->create('User', array('class' => 'form-horizontal', 'role' => 'form', 'div' => false, 'type' => 'file'));
echo $this->Form->input('username', array('label' => "Username"));
echo $this->Form->input('picture', array('label' => "Avatar", 'type' => 'file'));
echo $this->Form>formDefaultActions();
echo $this->Form->end();
?>
UserController.php:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
// set picture and path
$filedir = WWW_ROOT . 'userimages/';
$file = $filedir . $this->request->data['User']['picture']['name'];
// upload avatar picture
move_uploaded_file(
$this->request->data['User']['picture']['tmp_name'],
$file
);
$this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been added'), 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash(__('The user could not be created. Please, try again'), 'error');
}
}
}
现在是什么问题呢?笏不工作?我们的代码非常棒。 – 2014-10-16 14:59:38
它总是返回false,即使使用false,数据也不会写入数据库,但图像上传 – 2014-10-16 15:10:18
您检查图像是否已经存在于服务器上的FOLDER上。它不应该重复好吗? – 2014-10-16 15:54:26