Codeigniter上传文件不起作用

问题描述 投票:2回答:2
function submit_article() {
    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->form_validation->set_error_delimiters('<p style="color:red">', '<br/></p>');

    $my_rules = array(
        array(
            'field' => 'title',
            'label' => 'Title',
            'rules' => 'required|min_length[5]|max_length[20]|xss_clean'
        ),
        array(
            'field' => 'additionalUpload',
            'label' => 'Additional Upload',
            'rules' => 'callback_is_image'
        )
    );

    $this->form_validation->set_rules($my_rules);

    if ($this->form_validation->run() == FALSE) {
        //ERROR
        $data['title'] = ucfirst('submit Article');
        $this->load->view('templates/header', $data);
        $this->load->view('submit_article', $data);
        $this->load->view('templates/footer', $data);
    } else {
        //SUCCESS
        $data['title'] = ucfirst('article Submitted');
        $this->load->view('templates/header', $data);
        $this->load->view('forms_view/submit_article_success', $data);
        $this->load->view('templates/footer', $data);
    }
}

function is_image($value) {

    $config['upload_path'] = './public/uploads/';
    $config['allowed_types'] = 'gif|jpg|png|pdf|tiff';
    $config['max_size'] = '2048';
    $config['max_width'] = '0';
    $config['max_height'] = '0';
    $config['remove_spaces'] = true;

    $this->load->library('upload', $config);

    if (!$this->upload->do_upload()) {
        $this->form_validation->set_message('is_image', $this->upload->display_errors('<p style="color:red">', '<br/></p>'));
        return FALSE;
    } else {
        $this->upload->data();
        return TRUE;
    }
}

大家好,这是我的控制器功能代码,用于处理codeigniter中的多部分表单数据,实际上字段additionalUpload不是必需的字段,但是如果用户在文件类型的additionalUpload字段中上传文件,我想要验证它上面的代码并单击提交按钮而不选择任何文件,它显示错误“您没有选择要上传的文件”。这是我不想要的,因为这不是必填字段,这是我的第一个问题..

第二个是当我选择一个文件并点击提交按钮时,它再次显示“你没有选择要上传的文件。”。

注意:我刚刚在这里显示了我的表单的两个字段,即title,additionalUpload但我总共有9个字段。

提前感谢请帮助任何人。

php codeigniter file-upload image-uploading
2个回答
3
投票

首先要记住文件字段的名称。

<input type="file" name="image"/>
$this->upload->do_upload('image');

其次,你不能有max_width和max height 0

$config['max_width']    = '2048';
$config['max_height']   = '2048';

首先尝试,然后看看

对于验证字段文件:

if($_FILES['you_field_name']['tmp_name']){

       //your code  
}

一声问候


1
投票

尝试一下检查$_FILES是否为空,然后进行验证,否则什么都不做

 $my_rules = array(
        array(
            'field' => 'title',
            'label' => 'Title',
            'rules' => 'required|min_length[5]|max_length[20]|xss_clean'
        )
    );

if(!empty($_FILES)){

     $my_rules[]= array(
            'field' => 'additionalUpload',
            'label' => 'Additional Upload',
            'rules' => 'callback_is_image'
        )
}

$this->form_validation->set_rules($my_rules);

在上传功能中,您需要指定字段名称

$this->upload->do_upload('your_field_name')
© www.soinside.com 2019 - 2024. All rights reserved.