【问题标题】:Codeigniter Validation Not Working When Uploading Multiple Images Using Single Input使用单个输入上传多个图像时,Codeigniter 验证不起作用
【发布时间】:2019-02-25 08:35:46
【问题描述】:

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

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

这是我的 codeigniter 代码,

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

谁能告诉我为什么当我尝试在 codeigniter 中将图像名称更改为 images[] 时此验证不起作用,那么这将始终显示图像是必需的,而不是选择图像。

【问题讨论】:

标签: php codeigniter


【解决方案1】:

使用回调自己创建验证函数:

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;
    }
}

【讨论】:

  • @IkramKhizer,我测试了它,它工作得很好。
【解决方案2】:

尝试对$_FILES['images']['name'] 的计数应用验证。

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

【讨论】:

  • @IkramKhizer 你得到计数值了吗?
【解决方案3】:

您的输入名称是 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
}

【讨论】:

  • 在这种情况下不起作用,如果我上传图片然后它仍然说图片字段是必需的。
  • 我不明白您在 POST 上没有文件时调用表单验证是什么意思
【解决方案4】:

试试这个代码

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

【讨论】:

  • 更改输入标签中的id
  • 使用上面我在评论中提到的输入标签
  • 在表单标签中添加此代码:enctype="multipart/form-data"
  • 这样
    跨度>
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 2013-02-28
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多