Codeigniter以一种形式验证文件上传和文本输入 [英] Codeigniter validating file upload and text input in one form

查看:165
本文介绍了Codeigniter以一种形式验证文件上传和文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有文本输入和文件输入的表单。什么是正确的方法验证两个输入类型使用Codeigniter的验证库?我发现一些解决方案,但他们不能正常工作或看起来像一个overkill(创建新的库或修改CI系统文件)。

I have a form with text inputs and a file input. What is a proper way validate both input types using Codeigniter's validation library? I found some solutions but they don't work properly or seem like an overkill (creating new libraries or modifying CI system files).

在我看来,我使用1个多部分表单,同时显示文本验证错误和上传错误。

In my view I'm using 1 multipart form and displaying both text validation error and upload errors.

这是我到目前为止在我的控制器...

Here is what I have so far in my Controller...

function create() //create new post
{           
    $this->form_validation->set_rules('content', 'Entry', 'trim|required|xss_clean');
    $this->form_validation->set_rules('category_id', 'Category', 'trim|required|xss_clean|integer'); 

    //Text input fields
    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view('new_post');
    }       
    else
    {
            $config['upload_path'] = './uploads/posts/';
            $config['allowed_types'] = 'jpg|png';               
            $config['max_size'] = '800'; //in KB

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

            //File Upload
            if (! $this->upload->do_upload())
            {
                $upload_error['upload_error'] = array('error' => $this->upload->display_errors()); 

                $this->load->view('my_view', $upload_error);

                return FALSE;
            }

             //Add to database 
             $data = array (
               'user_id' => $this->tank_auth->get_user_id(),
               'category_id' => $this->input->post('category_id'),
               'content' => $this->input->post('content')
             );

             $this->Posts_model->create_post($data);

             $this->session->set_flashdata('success', 'Post_added!');
             redirect('posts');
    }       

}

c>您没有在我的视图中选择要上传的文件。

I keep getting You did not select a file to upload. in my view.

推荐答案

您的文件输入的名称? do_upload()期望它默认为userfile,但是如果你有像< input type =filename =image... 将需要调用 $ this-> upload-> do_upload('image')

What is the name of your file input? do_upload() is expecting it by default to be 'userfile', however if you have something like <input type="file" name="image"... you will need to call $this->upload->do_upload('image')

以确保表单设置为multipart - http://ellislab.com/codeigniter /user-guide/libraries/file_uploading.html

You also need to make sure the form is set to multipart - http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

这篇关于Codeigniter以一种形式验证文件上传和文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆