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