CodeIgniter - 表单验证和文件上载数据

时间:2011-03-03 06:25:51

标签: codeigniter file-upload validation

我想知道是否有一种方法可以使用CodeIgniter 2.0中的表单验证类来验证文件的大小。我有一个包含文件输入的表单,我想做这样的事情:

$this->form_validation->set_rule('file', 'File', 
                 'file_type[image/jpeg|image/gif|image/png]|file_max_size[500]');

我考虑过扩展验证类,将其与上传类组合,并根据上传数据进行验证,但这可能非常耗时。

有没有人知道表格验证类的任何扩展会做这样的事情吗?

2 个答案:

答案 0 :(得分:10)

文件上传类实际上有一套自己可以设置的验证规则

$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';

$this->load->library('upload', $config);

(taken from CI docs)

答案 1 :(得分:9)

我遇到了同样的问题。我建立了一个联系表单,允许用户上传头像并同时编辑其他信息。每个字段单独显示表单验证错误。我无法为文件输入和其他显示方案提供不同的显示方案 - 我有一个标准方法来处理显示错误。

我使用了控制器定义的属性和回调验证函数来将任何上传错误与表单验证合并。

以下是我的代码摘录:

# controller property

private $custom_errors = array();

# form action controller method

public function contact_save()
{
    # file upload for contact avatar

    $this->load->library('upload', array(
        'allowed_types'=>'gif|jpg|jpeg|png',
        'max_size'=>'512'
    ));

    if(isset($_FILES['avatar']['size']) && $_FILES['avatar']['size']>0)
    {
        if($this->upload->do_upload('avatar'))
        {           
            # avatar saving code here

            # ...
        }
        else
        {
            # store any upload error for later retrieval
            $this->custom_errors['avatar'] = $this->upload->display_errors('', '');
        }
    }

    $this->form_validation->set_rules(array(
        array(
            'field'   => 'avatar',
            'label'   => 'avatar',
            'rules'   => 'callback_check_avatar_error'
        )
        # other validations rules here
    );

    # usual form validation here

    if ($this->form_validation->run() == FALSE)
    {
        # display form with errors
    }
    else
    {
        # update and confirm
    }

}

# the callback method that does the 'merge'

public function check_avatar_error($str)
{
    #unused $str

    if(isset($this->custom_errors['avatar']))
    {
        $this->form_validation->set_message('check_avatar_error', $this->custom_errors['avatar']);
        return FALSE;
    }
    return TRUE;
}

注意:由于如果其他表单字段中存在任何错误,文件输入将不会重新填充,在上载成功时,我会在进行任何其他验证之前存储并更新它 - 因此用户无需重新选择该文件。如果发生这种情况,我的通知会有所不同。

相关问题