Codeigniter 使用空文件提交表单上载不起作用
在我的页面控制器上,我有一个用于主表单验证的回调函数,名为do_upload,它是我的文件上传 问题当我在没有上传图像的情况下提交表单时,会抛出错误Codeigniter 使用空文件提交表单上载不起作用,codeigniter,codeigniter-3,Codeigniter,Codeigniter 3,在我的页面控制器上,我有一个用于主表单验证的回调函数,名为do_upload,它是我的文件上传 问题当我在没有上传图像的情况下提交表单时,会抛出错误您没有选择要上传的文件。如果不上传图片,我可以提交表单的最佳方法是什么 <?php class Pages extends MX_Controller { public function __construct() { parent::__construct(); $this->load->
您没有选择要上传的文件
。如果不上传图片,我可以提交表单的最佳方法是什么
<?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');
}
和您遇到的问题没有太大关系,但有几点:1)不需要$this->load->library('form_validation')代码>在索引方法中,因为它在构造函数中,2.)避免CI框架使用的标准名称,如do_upload()
,3.)如果使用$this->upload->initialize($config)代码>在库加载中不需要第二个参数$this->load->library('upload')如果使用类的initialize()
方法,则为code>,反之亦然。