2017-05-29 50 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