使用单输入上传多个图像时,Codeigniter验证不起作用
问题描述:
I am trying to upload multiple images in codeigniter using single input its working fine but i also want to add codeigniter validation on this input field but it not works. Here's my html code,
<input type="file" name="images[]" id="file" multiple="">
And Here's my codeigniter Code,
if (empty($_FILES['images']['name']))
{
$this->form_validation->set_rules('images', 'Item Image', 'required');
}
Can anyone please tell me why this validation not working when i try to change images name to images[] in codeigniter then this will always says image is required rather the image is selected.
答
Create the validation function yourself using callback:
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;
}
}
答
Try to apply validation on the count of $_FILES['images']['name']
.
if (count($_FILES['images']['name']) < 1)
{
$this->form_validation->set_rules('images', 'Item Image', 'required');
}
答
Try this code
if (count($_FILES['images']['name']) == 0)
{
$this->form_validation->set_rules('images', 'Item Image', 'required');
}
答
Your input name is name="images[]" So try this one...
$this->form_validation->set_rules('images[]', 'Item Image', 'required');
So you can call form validation when you have no files on POST.
if(count($_FILES['images']['name']) < 1) {
$this->form_validation->set_rules('images[]', 'Item Image', 'required');
}else {
// upload files
}