使用单个输入上传多个图像时,Codeigniter验证不起作用

时间:2019-02-25 08:35:47

标签: php codeigniter

我正在尝试使用单个输入在codeigniter中上传多个图像,但其效果还不错,但我也想在此输入字段上添加codeigniter验证,但它不起作用。 这是我的html代码,

<input type="file" name="images[]" id="file" multiple="">

这是我的代码点火器代码,

if (empty($_FILES['images']['name']))
{
    $this->form_validation->set_rules('images', 'Item Image', 'required');
}

有人可以告诉我为什么当我尝试在codeigniter中将图像名称更改为images []时,此验证为什么不起作用,然后总是表示需要图像而不是选择图像。

4 个答案:

答案 0 :(得分:0)

尝试对$_FILES['images']['name']的数量进行验证。

if (count($_FILES['images']['name']) < 1)
{
   $this->form_validation->set_rules('images', 'Item Image', 'required');
}

答案 1 :(得分:0)

尝试此代码

if (count($_FILES['images']['name']) == 0)
{
     $this->form_validation->set_rules('images', 'Item Image', 'required');
}

答案 2 :(得分:0)

您输入的名称为 name =“ images []” 所以试试这个...

$this->form_validation->set_rules('images[]', 'Item Image', 'required');

因此,当POST上没有文件时,您可以调用表单验证。

if(count($_FILES['images']['name']) < 1) {
    $this->form_validation->set_rules('images[]', 'Item Image', 'required');
}else {
   // upload files
}

答案 3 :(得分:0)

使用回调自己创建验证功能:

public function index()
{
    $this->load->helper('file');
    $this->load->library('form_validation');
    if($this->input->post('submit'))
    {
        $this->form_validation->set_rules('file', '', 'callback_file_check');
        if($this->form_validation->run() == TRUE)
        {
            // Upload
        }
    }
    $this->load->view('upload');
}

public function file_check($str)
{
    $allowed_mime_type_arr = array('image/gif','image/jpeg','image/png');
    $mime = get_mime_by_extension($_FILES['file']['name']);
    if(isset($_FILES['file']['name']) && $_FILES['file']['name']!="")
    {
        if(in_array($mime, $allowed_mime_type_arr))
        {
            return TRUE;
        }
        else
        {
            $this->form_validation->set_message('file_check', 'Please select only gif/jpg/png file.');
            return FALSE;
        }
    }
    else
    {
        $this->form_validation->set_message('file_check', 'Please choose a file to upload.');
        return FALSE;
    }
}