2011-08-25 48 views
4

即時通訊嘗試上傳帶有標題和說明的圖像以及圖像上傳。我的圖片上傳和文本輸入單獨工作,文本和圖像路徑也被插入到數據庫,但我仍然無法人物如何既上傳圖像並在codeigniter中插入文本

結合我以前在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數據庫中?

回答

3

基本上,只要把圖片上傳輸入相同的形式,如:

// 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); 
    } 
} 

您還需要進行適當的模型來輸入數據庫中的數據。

+0

非常感謝:) – LiveEn

+0

你好@Woxxy好的答案。但是如果圖像上傳是可選的更新。在這種情況下做什麼? –