我正在编写一个脚本,该脚本将上传图像并将图像路径保存在数据库中。我遇到的唯一问题是,如果用户没有上传图像,我想设置默认图像。
但是在 codeigniter 中,当未选择图像时,它会自动给出错误,指出尚未选择输入文件。
我的 Controller
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']
查看是否选择了文件。
关于php - 如果在 codeigniter 中没有选择上传图像,则设置默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519688/