我有一个带有一些输入的表单和一个可选的文件上传按钮。现在,每当我在不上传图像的情况下提交表单时,就会出现错误"您没有选择要上传的文件"。我想避免此错误,因为我可能并不总是需要上传图像。无论如何有什么可以做的吗?提前致谢。我用于添加文件的控制器如下:
public function add_admin()
{
$this->data['main_content'] = 'admin/admin_config/index';
$this->data['sub_content'] = 'admin/admin_config/admin_form';
$this->load->view(BACKEND, $this->data);
}
public function store_admin()
{
$post = $this->input->post();
unset($post['designation'], $post['password'], $post['re_pass']);
$post['password'] = sha1($this->input->post('password'));
$post['designation'] = implode(', ', $this->input->post('designation'));
$c_pass = sha1($this->input->post('re_pass'));
$image_name = $_FILES['admin_image'];
$post['filename'] = $image_name['name'];
$config = [
'upload_path' => './upload/admin/',
'allowed_types' => 'jpg|jpeg|png',
];
$this->load->library('upload', $config);
if ($post) {
if ($post['password'] == $c_pass && $this->upload->do_upload('admin_image')) {
$this->adminconfig_model->insert($post);
set_flash('msg', 'Admin added Successfully!!');
redirect('admin/adminConfig');
}else{
$this->data['error_image'] = $this->upload->display_errors();
$this->add_admin();
}
} else {
set_flash('dmsg', 'Password do not match!!');
$this->add_admin();
}
}
基本上,您需要避免通过检查$_FILES
数组是否填充不存在的图像。如果没有上传图像,上传库将始终丢弃该错误。
您也有一些奇怪的逻辑if ($post)
始终将其评估为true,因此我们真的不需要它。此外,似乎您的"错误密码"消息在错误的位置。
以下代码将有助于解决这些错误并稍微清理您的代码:
public function store_admin() {
// post stuff
$data = array(
'designation' => implode(', ', $this->input->post('designation')),
'password' => sha1($this->input->post('password')),
'filename' => ''
);
$c_pass = sha1($this->input->post('re_pass'));
// first check if passwords match
if ($data['password'] !== $c_pass) {
set_flash('dmsg', 'Passwords do not match!');
$this->add_admin();
} else {
$upload = true; // general flag, will be overriden with errors should they occur
// check if image is uploaded
if (!empty($_FILES['admin_image']['tmp_name'])) {
$config = [
'upload_path' => './upload/admin/',
'allowed_types' => 'jpg|jpeg|png',
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('admin_image')) {
$upload = $this->upload->display_errors();
} else {
// add filename from upload function
// should do it this way because if overwrite is false
// upload library will append _1 to the image if it already exists
$post['filename'] = $this->upload->data('file_name');
}
}
if ($upload !== true) {
$this->data['error_image'] = $upload;
$this->add_admin();
} else {
$this->adminconfig_model->insert($data);
set_flash('msg', 'Admin added successfully!');
redirect('admin/adminConfig');
}
}
}