提交表单,空文件上传不起作用

时间:2015-05-19 14:35:41

标签: codeigniter codeigniter-3

在我的页面控制器上,我有一个回调函数用于我的主表单验证,名为 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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我解决了自己的问题:

在主表单验证中,我添加了一个isset和&amp;&amp; !对于设定规则是空的,现在它正在运作。

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