上传图片并在codeigniter中插入文本
Posted
技术标签:
【中文标题】上传图片并在codeigniter中插入文本【英文标题】:upload image and insert text in codeigniter 【发布时间】:2011-11-04 00:03:22 【问题描述】:我正在尝试上传带有标题和描述的图像以及图像上传。我的图片上传和文本输入分开工作,文本和图片路径也插入到数据库中,但我仍然不知道如何将两者结合起来
我使用了http://codeigniter.com/user_guide/libraries/file_uploading.html中给出的指南
function do_upload()
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
else
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
谁能告诉我如何将一些文本字段与图像上传表单一起插入到 sql 数据库中?
【问题讨论】:
【参考方案1】:基本上只要把图片上传input放在同一个表单中,比如:
// view
echo form_open_multipart('controller_name/do_upload');
echo form_input("title", "");
echo form_input("description", "");
echo form_upload("userfile");
echo form_close
并在控制器中添加 POST 读数:
// controller
function do_upload()
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
// validate the POST data
// http://codeigniter.com/user_guide/libraries/form_validation.html
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('description', 'Description', 'trim|required')
if ($this->form_validation->run() == FALSE)
// failed validation
$this->load->view('myform');
// quit here
return false;
if ( ! $this->upload->do_upload())
// no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
else
// success
$data = array('upload_data' => $this->upload->data());
$title = $this->input->post('title');
$description = $this->input->post('description');
// a model that deals with your image data (you have to create this)
$this->your_upload_model->add($title, $description, $data["file_name"]);
$this->load->view('upload_success', $data);
您还需要建立一个合适的模型来将数据输入数据库。
【讨论】:
你好@Woxxy 不错的答案。但是如果图像上传是可选的更新怎么办。在那种情况下该怎么办?以上是关于上传图片并在codeigniter中插入文本的主要内容,如果未能解决你的问题,请参考以下文章
Summernote 图像上传在 codeigniter 中不起作用