2017-05-29 49 views
0

我想從文件夾改變笨的圖像,取代先前上傳的圖片,並刪除以前的圖片:想改變笨

這裏是我的控制器。但它不工作:

public function changeImage(){ 

    //$user_id = $this->profile_model->changeImage(); 

     /************* File Upload ************/ 
     $config['upload_path'] = './uploads/user_pic/'; 
     $config['allowed_types'] = 'gif|jpg|png|jpeg'; 
     $this->load->library('upload',$config); 

     $filetype = $_FILES['user_pic']['type']; 
     $file_name = $_FILES['user_pic']['name']; 

     if($filetype == "image/jpg") 
       $file_type='jpg'; 
      else if ($filetype == "image/gif") 
       $file_type='gif'; 
      else if($filetype == "image/jpeg") 
       $file_type='jpg'; 

      else if($filetype == "image/pjpeg") 
       $file_type='pjpeg'; 
      else if($filetype == "image/png") 
       $file_type='png'; 

     $_FILES['user_pic']['name']=$user_id.'.'.$file_type; 

     $this->upload->do_upload('user_pic'); 


     $up_dtat = array('user_pic' => $_FILES['user_pic']['name']); 
     $this->db->where('user_id',$user_id); 
     $this->db->update('tbl_users',$up_dtat); 
    redirect('profile'); 
} 

回答

1

,如果您需要在您的商店文件更新資料圖片,首先你需要刪除舊文件,用戶ID的基礎取舊的文件名。

然後用此代碼給出文件名。

unlink("your_path/filename.jpg"); //don't use base_url() just give the path like profile_pic/xxxxx.png 

此代碼將從該文件夾中刪除指定的文件。

現在我有用於文件上傳的代碼,所以它也適用於您嘗試此操作。

$imgpath='uploads/profile_pic/';//path where do you want to store image 
      $all_img=""; 
      if($_FILES["profile_pic"]['name'])//input type that you have use in file upload 
      {   
       $path_parts = pathinfo($_FILES["profile_pic"]["name"]); 
       $image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension']; 
       $all_img.=$image_path; 
       move_uploaded_file($file_tmp=$_FILES["profile_pic"]["tmp_name"],$imgpath."/".$image_path); 
       $data['cm_user_profile_pic']=$all_img;//store filename in array to update in database 
      } 
0

如果要替換以前的形象只不過設置文件名相同,則

第一種方法是:

從表

$sql = "SELECT user_pic FROM tbl_users WHERE user_id=?"; 
$get_image = $this->db->query($sql,array($user_id))->row_array(); 

集變老的文件名分配給舊的新文件名

$config['file_name'] = $get_image['user_pic']; 
$config['overwrite'] = TRUE; // this will overwrite your image 
$this->load->library('upload', $config); 

但在這種情況下,舊文件和新的文件擴展名必須是相同的 如果兩個擴展名不同的話,說不定圖像將上傳後墜毀

第二種方法是

獲得來自user_pic數據DB

及取消該照片

unlink($_SERVER['DOCUMENT_ROOT'].'/'.Your_image_folder.$get_image['user_pic']); 

和CH ECK文件上傳或不

if (! $this->upload->do_upload('user_pic')) { 
      $error = array('error' => $this->upload->display_errors()); 
     } 

     else { 
      $data = array('upload_data' => $this->upload->data()); 
     } 
+0

不工作...請您在最後的評論我的編輯功能@Nidhi – Sabbir

+0

解釋我發出@Sabbir ...不工作,但在這種情況下?圖像沒有被覆蓋或不刪除? – Nidhi