繁体   English   中英

文件验证不适用于蛋糕php

[英]File validation is not working in cake php

如果我不选择文件,则时间验证不起作用,并且不显示消息“无效文件”。

这是动作网址:

HTTP://本地主机/ carsdirectory /汽车/ create_ad

create_ad.ctp(视图)

 <?php echo $this->Form->create('Car', array('type' => 'file', 'action' => 'create_ad')); ?>

      <?php echo $this->Form->file('CarImage.image_path')?>

<?php echo $this->Form->end(array('label' => 'Submit', 'name' => 'Submit', 'div' => array('class' => 'ls-submit')));?>

car_image.php(模型)

 <?php
 class CarImage extends AppModel
 {
 var $name = 'CarImage';

 var $belongsTo = 'Car';

 var $validate = array(

 'image_path' => array(

 'rule' => array('extension', array('jpeg', 'jpg', 'png', 'gif')),

 'allowEmpty' => false,

 'required' => true,

 'message' => 'invaid file'
        ),

  'car_id' => array(
          'rule' => "numeric",
           'allowEmpty' => false,
           'message' => 'Car details could not be saved'
      )


       );
 }
 ?>

car_images(表)

字段 - > 1)id 2)image_path 3)car_id

正如我评论并建议根据您的方案似乎正确的是您有这些关联:

汽车模型:

public $hasMany = array(
    'CarImage' => array(
        'className' => 'CarImage',
        'foreignKey' => 'car_id',
        'dependent' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ), 
);

CarImage型号:

public $belongsTo = array(
    'Car' => array(
        'className' => 'Car',
        'foreignKey' => 'car_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

表单字段,因为您可以上传许多文件(只需使用数字增量创建一个新行):

echo $this->Form->file('CarImage.0.image_path');

要验证和上传文件,在CarImage模型中更容易和更一致(我不确定你是否需要$ validate变量中的car_id,如果不起作用,请尝试从$ validate中删除car_id):

public $validate = array(
    'image_path' => array(
        'uploadFile' => array(
            'rule' => array('uploadFile'),
            'message' => 'Invalid file',
        ),
    ),
);

public function uploadFile($params) {
    if ($params['image_path']['error'] == 0) {
        $file = pathinfo($params['image_path']['name']);

        if (in_array($file['extension'], array('jpeg', 'jpg', 'png', 'gif'))) {
            $tmp_file = new File($params['image_path']['tmp_name']);
            if ($tmp_file->copy('folder_inside_webroot' . DS . $file['basename'])) {
                return true;
            }
        }
    }

    return false;
}

而你的控制器需要saveAll而不是save

if ($this->Car->saveAll($this->data)) {
    // success
} else {
    // failure
}

我希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM