有一个包含4个文本字段的表单,名称,移动,电子邮件和图像。但是,“图像”字段是可选的。当我提交数据而不插入图像时,它显示“您未选择要上传的文件”。解决方法。
我的控制器功能是:
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());
}
答案 0 :(得分:2)
检查该键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());
}