2012-07-07 75 views
4

我使用Codeigniter的File Uploading Class上傳用戶頭像。有沒有辦法在他/她上傳新圖像文件時替換用戶的圖像文件?我想用最新的頭像替換現有的頭像。Codeigniter替換上傳的圖像

我的圖片上傳控制器

function upload_avatar() 
    { 
     $config['upload_path'] = './uploads/avatars/'; 
     $config['allowed_types'] = 'jpg|png'; 
     $config['overwrite'] = FALSE; //overwrite user avatar 
     $config['encrypt_name'] = TRUE; 
     $config['max_size'] = '200'; //in KB 

     $this->load->library('upload', $config); 

     if (! $this->upload->do_upload()) 
     { 
      $error = $this->upload->display_errors(); 

      $this->session->set_flashdata('error', $error); 

      redirect('/settings/avatar'); 
     } 
     else 
     {     
      $config['image_library'] = 'gd2'; 
      $config['source_image'] = $this->upload->upload_path.$this->upload->file_name; 
      $config['create_thumb'] = FALSE; 
      $config['maintain_ratio'] = FALSE; 
      $config['width'] = 120; 
      $config['height'] = 120; 

      $this->load->library('image_lib', $config); 

      $this->image_lib->crop(); 

      //Add image path to database 
      $avatar_path = 'uploads/avatars/' . $this->upload->file_name; 
      $user_id = $this->tank_auth->get_user_id(); 
      $this->Settings_model->update_avatar($avatar_path, $user_id); 

      $this->session->set_flashdata('success', 'Avatar updated!'); 

      redirect('/settings/avatar'); 
     } 
    } 
+2

你有沒有嘗試設置此行'$配置[ '覆蓋'] = FALSE; //將用戶頭像「覆蓋爲」真「? – drfranks3 2012-07-07 04:31:01

+0

我會現在。謝謝! – CyberJunkie 2012-07-07 21:07:08

回答

8

有一個公共屬性overwrite該規定覆蓋原文件的決定。默認情況下,會根據原始文件創建一個新文件名。下面是upload.php的在CI源:

/* 
* Validate the file name 
* This function appends an number onto the end of 
* the file if one with the same name already exists. 
* If it returns false there was a problem. 
*/ 
$this->orig_name = $this->file_name; 

if ($this->overwrite == FALSE) 
{ 
    $this->file_name = $this->set_filename($this->upload_path, $this->file_name); 

    if ($this->file_name === FALSE) 
    { 
     return FALSE; 
    } 
} 

因此,所有你需要做的就是重寫工作是:

$this->load->library('upload', $config); 
$this->upload->overwrite = true; 
+0

謝謝!爲了替換工作,我認爲我必須爲每個頭像圖像提供一個唯一的名稱,例如用戶的用戶名。這樣用戶上傳的任何內容都會替換已存儲的內容。 – CyberJunkie 2012-07-07 21:01:31

5

簡單的設置「超越控制」是在你的配置真。

$this->upload->initialize(array(
      "upload_path"=>$path, 
      "allowed_types"=>"jpg|png|jpeg", 
      "overwrite"=>true 
     )); 
0

做你試圖改變

$config['overwrite'] = FALSE; 

$config['overwrite'] = TRUE;