如果没有选择要在codeigniter中上传的图像,则设置默认图像


Set default image if no image is selected to upload in codeigniter

我正在做一个脚本,将上传图像并保存在数据库中的图像路径。我遇到的唯一问题是,如果用户不上传图像,我想设置一个默认图像。

但是在codeigniter中,当一个图像没有被选中时,它会自动给出一个错误,说输入文件没有被选中。

我的控制器

  if ( !$this->upload->do_upload('image'))
     {
    $error = array('error' => $this->upload->display_errors());
    $this->load->view('upload_success', $error);
     }
    else {
        $image_data=array('image_info' => $this->upload->data('image')); 
        $image_path=$image_data['image_info']['full_path'];
        $data =array(
        'submitedby'=>$username,
        'city'=>$this->input->post('towncity'),
        'image' => $image_path
);  
   }

有人可以建议我如何设置一个默认的图像,如果用户没有选择一个图像而不显示默认的错误?

do_upload()失败的子句中,检查文件是否上传。

if (!$this->upload->do_upload('image')) {
    if (!empty($_FILES['image']['name'])) {
        // Name isn't empty so a file must have been selected
        $error = array('error' => $this->upload->display_errors());
        $this->load->view('upload_success', $error);
    } else {
        // No file selected - set default image
        $data = array(
            'submitedby' => $username,
            'city'       => $this->input->post('towncity'),
            'image'      => 'path/to/default/image',
        );
    }
} else {
    $image_data = array('image_info' => $this->upload->data('image'));
    $image_path = $image_data['image_info']['full_path'];
    $data = array(
        'submitedby' => $username,
        'city'       => $this->input->post('towncity'),
        'image'      => $image_path,
    );
}

这可以进一步重构,但关键是您可以检查$_FILES['field_name']['name']以查看是否选择了文件。

你可以不让图像字段必需,然后你可以在你的视图中设置一个默认的图像,如果没有找到的图像。这样你就不会有各种重复的图片被上传,你就可以随时为每个人更新你的默认图片。