CakePHP:如果文件不工作,则验证表单上载字段

CakePHP:如果文件不工作,则验证表单上载字段,php,validation,cakephp,Php,Validation,Cakephp,CakePHP2.x:我正在努力验证表单中用于添加用户的图像上传字段。上载字段不是manditory。但是在上传图像时,它总是将字段验证为false。整个验证似乎部分起作用。任何帮助都将不胜感激 User.php模型: public $validate = array( 'picture' => array( 'required' => false, 'allowEmpty' => true, 'custom' =>

CakePHP2.x:我正在努力验证表单中用于添加用户的图像上传字段。上载字段不是manditory。但是在上传图像时,它总是将字段验证为false。整个验证似乎部分起作用。任何帮助都将不胜感激

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(); 
?>

您需要在上传之前检查您的验证,否则将始终为false。若上传文件,当cakephp验证文件夹中已经存在文件时

您只需将逻辑移到如下位置:

$this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
if ($this->User->save($this->request->data)) {
    move_uploaded_file(
        $this->request->data['User']['picture']['tmp_name'],
        $file
    );
}
或在保存前检查:

if ($this->User->validates()) {
    if ($this->User->save($this->request->data)) {
        move_uploaded_file(
            $this->request->data['User']['picture']['tmp_name'],
            $file
        );
    }
}
对此发表评论

  $this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
并将这两条语句放入model、required和allowEmpty中。同时在控制器中替换:

if ($this->User->save($this->request->data))


pic名称应该保存到db中

现在有什么问题?wat不工作?你的代码很棒。它总是返回false,即使返回false,数据也不会写入数据库,但图像已上载。请检查服务器上的文件夹中是否已存在图像。确定??它不应该重复ok??提供用户控制器代码u写保存在数据库中的图像+图像上传Hi Angry Bird。。。刚刚更新了初始问题并添加了controllerOP的代码是正确的,
$this->User->save($this->request->data))
是完全有效的,我在每个项目中都使用了它。这是我的一个习惯,两种解决方案都是有效的,如果验证成功,->那么只将图像名称保存在DB中,然后上传文件+1 :)
if ($this->User->save($this->request->data))
if ($this->User->save($this->request->data['User']))