在我的页面控制器上,我有一个回调函数,用于我的主表单验证,称为do_upload,这是我的文件上传。
问题当我提交我的表单没有上传图像时,它抛出错误You did not select a file to upload
。什么是最好的方法,所以我可以提交表单,如果不上传图像。
<?php
class Pages extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$page_info = $this->get_page_info($this->uri->segment(5));
$data['page_name'] = $page_info['page_name'];
$data['page_description'] = $page_info['page_description'];
$data['page_image'] = $page_info['page_image'];
$data['page_status'] = $page_info['page_status'];
if ($page_info['page_image'] == TRUE) {
$data['main_page_image'] = $this->resize($page_info['page_image']);
} else {
$data['main_page_image'] = "";
}
$results = $this->get_page_extra_images();
foreach ($results as $result) {
$data['popup_images'][] = array(
'page_extra_image_id' => $result['page_extra_image_id'],
'image' => $result['page_extra_image'],
'src' => $this->resize($result['page_extra_image'])
);
}
$this->load->library('form_validation');
$this->form_validation->set_rules('page_name', 'Page Name', 'required|callback_do_upload');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/catalog/page_form_view', $data);
} else {
redirect('admin/catalog/pages');
}
}
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '30000';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$this->form_validation->set_message('do_upload', $this->upload->display_errors());
return FALSE;
} else {
return TRUE;
}
}
}
我解决了我自己的问题:
在主表单验证中,我添加了一个isset和&&
if (isset($_FILES['userfile']['name']) && !empty($_FILES['userfile']['name'])) {
$this->form_validation->set_rules('page_name', 'Page Name', 'required|callback_do_upload');
} else {
$this->form_validation->set_rules('page_name', 'Page Name', 'required');
}