如何在 codeigniter 中使图像上传可选?

How to Make Image upload optional in codeigniter?

有一个表单有 4 个文本字段,姓名、手机、电子邮件和图片。但是图像字段是可选的。当我提交数据而不插入图像时,它显示 "You did not select a file to upload"。如何解决。

我的控制器功能是:

public function addAgent(){
$this->form_validation->set_rules('AgentName','AgentName','required');
$this->form_validation->set_rules('mobile','mobile','required');
$this->form_validation->set_rules('email', 'email', 'required');
if ($this->form_validation->run() == FALSE) {   
$this->session->set_flashdata('registerMessage',errors(),':old:');
redirect(base_url());
}else{
$config['upload_path']          = './uploads';
$config['allowed_types']        = 'gif|jpg|png';
$config['max_size']             = 50000;
$config['max_width']            = 10240;
$config['max_height']           = 7680;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image'))
{
$this->session->set_flashdata('registerMessage',$this->upload->display_errors(),':old:');
redirect(base_url());
}
else
{
$dataUpload = $this->upload->data();
$filename = $dataUpload['file_name'];
}
}
$data = array(
'AgentName'         =>  $this->input->post('AgentName'),
'mobile'        =>  $this->input->post('mobile'),
'image'          =>  $filename,
'email'         =>  $this->input->post('email')
);
$this->general_model->insert('agent',$data);
$this->session->set_flashdata('registerMessage','AddedSuccessfully',':old:');
redirect(base_url());
}

检查该键 image 的文件数组是否已填充以及它是否具有 tmp_name:

public function addAgent() {
    $this->form_validation->set_rules('AgentName', 'AgentName', 'required');
    $this->form_validation->set_rules('mobile', 'mobile', 'required');
    $this->form_validation->set_rules('email', 'email', 'required');
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('registerMessage', errors(), ':old:');
        redirect(base_url());
    }
    $filename = ''; // init as blank otherwise notice
    if (isset($_FILES['image']) && !empty($_FILES['image']['tmp_name']))  {
        $config['upload_path'] = './uploads/'; // should have slash at end
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = 50000;
        $config['max_width'] = 10240;
        $config['max_height'] = 7680;
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('image')) {
            $this->session->set_flashdata('registerMessage', $this->upload->display_errors(), ':old:');
            redirect(base_url());
        } else {
            $dataUpload = $this->upload->data();
            $filename = $dataUpload['file_name'];
        }
    }
    $data = array(
        'AgentName' => $this->input->post('AgentName'),
        'mobile' => $this->input->post('mobile'),
        'image' => $filename,
        'email' => $this->input->post('email')
    );
    $this->general_model->insert('agent', $data);
    $this->session->set_flashdata('registerMessage', 'AddedSuccessfully', ':old:');
    redirect(base_url());
}