验证始终是触发规则消息

时间:2014-04-24 14:17:03

标签: validation cakephp file-upload

我的图片上传验证总是触发与要上传的文件的允许大小相关的消息,之后我将代码复制到验证数组的顶部,其中previouslly是is_valid规则,即使文件大小低于限制,甚至文件上传成功,也会始终触发。我的is_unique规则按预期工作,但其余的似乎总是被触发,即使文件遵守规则。什么是触发此行为? 我正在使用CakePHP 2.4.4。

控制器

public function admin_upload_image(){
        $this->set('title_for_layout', 'Inserir Fotografias');
        if(!$this->Session->check('User')) {
            $this->Session->setFlash('Está a aceder a uma zona restrita. Por favor faça Login.');
            $this->redirect(array(
                            'controller' => 'users',
                            'action' => 'login'));
        }

        $this->layout = 'admin_index';
        if($this->request->is('post') || $this->request->is('put')) {
          /*  $file = $this->request->data['gallery_images']['path']['name'];*/
       //debug($this->request->data['gallery_images']['path']['name']);
       //die;
        $file = array(
                'GalleryImage' => array(
                'path' => $this->request->data['gallery_images']['path']['name']
                                        )
                );
            move_uploaded_file($this->data['gallery_images']['path']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/html/PushUp/app/webroot/img/gallery/' . $this->data['gallery_images']['path']['name']);

            $this->loadModel('GalleryImage');

            $this->GalleryImage->create();
           //debug($file);
           //die;
            if($this->GalleryImage->save($file)){
                $validationErrors = $this->GalleryImage->invalidFields();
                $this->Session->setFlash($validationErrors['path']); // named key of the rule
                $this->Session->setFlash('Fotografia guardada com sucesso.', 'default', array('class'=>'alert alert-success'));
            }
            //else{
                //debug($this->GalleryImage->invalidFields());
                //die;
                //$error = $this->Notification->validationErrors;
                //$this->set('error', $error);

                //$this->Session->setFlash(__($error), 'Flash/warning');
            //}
        }
    } 

模型

<?php
App::uses('AppModel', 'Model');
class GalleryImage extends AppModel{
    public $displayField ='path';
    public $useTable = 'gallery_images';
    //public $actsAs = array('MultipleDisplayFields' => array('fields' => array('path', 'id')));
    var $name = 'GalleryImage';
    var $validate= array(
        'path' => array(

            'size' => array(
                'rule' => array('fileSize','<=','1.5MB'),
                'message' => 'O ficheiro deve ter um tamanho igual ou inferior a 1.5MB.',
                //'last' => true,
                'required'=> true),
            'is_valid' => array(
                'rule' => 'fileSelected',
                'message' => 'Seleccione uma fotografia por favor.',
                //'last' => true,
                'required'=> true),
            'extension' => array(
                'rule' => array('extension', array('gif','jpeg','png','jpg')),
                'message'=> 'A imagem deve estar num formato gif, jpeg, png ou jpg.',
                //'last' => true,
                'required'=> true),
            'is_unique' => array(
                'rule' => 'isUnique',
                'message' => 'Uma fotografia com este nome já existe.',
                'required'=> true
                )
            )
        );


/*public function isUploadedFile($params) {
    $val = array_shift($params);
    if ((isset($val['error']) && $val['error'] == 0) || (!empty( $val['tmp_name']) && $val['tmp_name'] != 'none')) {
        return is_uploaded_file($val['tmp_name']);
    }
    return false;
}*/
public function fileSelected($file) {
if(is_array($file) && array_key_exists('path', $file) && !empty($file['path'])) {
    // Seems like a file was set
    return true;
}

// No file set, doesn't validate!
return false;
}
}
?>

查看

<style>
.alert-warning{
    width:100%;
}
.error-message{


}
.col-lg-4{
    width:100%;
}
</style>

<h2>Apagar Fotografia</h2>
<?php echo $this->Session->flash();?>
<br>
<table border="1" bordercolor="#e2e2e2"  width="720" style="word-wrap: break-word" cellpadding="5px" class="">
<tr>
    <?php
        $i=0;
        foreach( $gallery_images as $gallery_image ):?>

        <?php
            echo "<td style=text-align: justify>";
            //echo $gallery_image['GalleryImage']['path'];
            echo $this->Form->postLink('Apagar', array('controller'=>'Galleries', 'action'=>'admin_del_image', $gallery_image['GalleryImage']['id']/*,'prefix'=>'admin'*/), array('class'=>'foto_del btn btn-danger', 'title'=>'Apagar Fotografia'), __('Tem a certeza que quer apagar esta Fotografia?'));
            echo "</td>";
            echo "<td>";
            //$src3 =$this->webroot. 'img/gallery/' .$gallery_image['GalleryImage']['path'];
            echo $this->Html->image('gallery/' . $gallery_image['GalleryImage']['path'] , array('width' => '200px', 'height' => '133px', 'alt' => $gallery_image['GalleryImage']['path'] )); 
            echo "</td>";
            $i++;
            if($i==4){
                echo "</tr><tr>";
                $i=0;   
            }
        ?>
        <?php endforeach ?>
</tr>

</table>

1 个答案:

答案 0 :(得分:3)

您正在传递$ file变量以进行保存 的 $这 - &GT; GalleryImage-&GT;保存($文件)

并且您手动设置此变量值

$file = array(
          'GalleryImage' => array(
          'path' => $this->request->data['gallery_images']['path']['name']
      )
);

因此您不会将文件信息传递给您的模型。您必须将 $ this-&gt; request-&gt;数据[&#39; gallery_images&#39;] [&#39;路径&#39;] 传递给您的保存方法