繁体   English   中英

在 php Codeigniter 上传用户头像

[英]Upload user profile picture in php Codeigniter

如何根据 user_id 上传用户个人资料图片? 我正在尝试让每个特定用户能够在他们的个人资料上上传照片并存储在数据库中。 我不知道如何处理这个要求,所以我在这里提供了我的代码,如果你能帮助我如何处理,我将不胜感激。 这是我的个人资料。php 视图

<div class="profile-img">
                <?php if (!empty($user->photo)): ?>
               <img src="/uploads/<?php echo $user->photo; ?>" alt="<?php echo $user->photo; ?>">
                  <?php endif;?>
                  <!-- <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS52y5aInsxSm31CvHOFHWujqUx_wWTS9iM6s7BAm21oEN_RiGoog" alt=""/> -->
                  
                  <?php echo form_open_multipart('users'); ?>
                   <input type="hidden" name="user_id" value="<?php echo $user->id; ?>" />
                 <div class="file btn btn-lg btn-primary">
                     <i class="fa fa-pencil-square-o"></i>
                      <input type="file" name="file" />
                      <input type="submit"  name="submit" value="Upload photo" />
                </form>
                
                </div>
            </div>

这是我的 Profile.php Controller 在这里我获得了我的个人资料视图所需的所有详细信息。

    function index()
{

     $user_id =  $this->session->userdata('admin');
    if(empty($user_id)){
         redirect('admin/login');
     }
    
   $data['userInfo'] = $this->profile_model->myProfile($user_id);
    
     if($user_id == 3){ // admin
        $data['project12'] = $getAllProjects = $this->profile_model->getAdminProjects();

        //echo '<pre>';
        //print_r($getAllProjects);
        //die;
        $new_array = array();
        foreach($getAllProjects as $key => $row) {
            $new_array[$key]['id'] = $row->id; 
            $new_array[$key]['delete_flag'] = $row->delete_flag; 
            $new_array[$key]['project_name'] = $row->project_name; 
            $new_array[$key]['client_name'] = $row->client_name; 
            $new_array[$key]['company'] = $row->company; 
            $new_array[$key]['project_manager'] = $row->project_manager; 
            $sec_array = explode(",",$row->support_staff);
            if(is_array($sec_array) ){
                foreach($sec_array as $row1){
                    $new_array[$key]['support_staff'][] = $this->profile_model->getUsernameByID($row1);

                }
            }
        }
        
        //print_r($new_array);die;
        $data['project'] = $new_array;

        $data['task_list'] = $this->task_model->getAllTasks();

        $data['incident_list'] = $this->incidents_model->getAllIncidents();


//      echo "<pre>";
// print_r($data['incident_list']);
//      die;

     }else{ // others
         $data['project'] = $this->profile_model->getById_myProjects($user_id);
         $data['task_list'] = $this->task_model->getTaskByUserID($user_id);
         $data['incident_list'] = $this->incidents_model->getIncidentByUserID($user_id);

     }
    if ($this->input->server('REQUEST_METHOD') == 'POST') 
    {
    $this->upload_photo();
    }else{
    $this->load->view('users', [
    //'errors' => $this->upload_errors,
    'users'  => $this->profile_model->get_all()]);
    }



     $this->load->view('admin/profile/index',$data);
}


     $this->load->view('admin/profile/index',$data);
}
private function upload_photo()
    {
    $user_id = $this->input->post('user_id');
    $existing_photo = $this->profile_model->get_photo($user_id)->photo;
    if ($existing_photo && file_exists("./uploads/{$existing_photo}")) {
        unlink("./uploads/{$existing_photo}");
    }
    if (!$this->upload->do_upload('photo')) {
        $this->upload_errors = $this->upload->display_errors();
    }
    $photo = $this->upload->data()['file_name'];
    $this->profile_model->update_photo($user_id, $photo);
   }

这是我的 profile_model

function get_all($user_id)
 {
     $query = $this->db->query("SELECT * FROM profile_details where user_id =$user_id");
      return $query->result();

 }


 function get_photo()
{
$query = $this->db->query("SELECT photo FROM profile_details where user_id= $user_id");

}


function update_photo($user_id, $photo)
{
    $this->db->update('profile_details', ['photo' => $photo], ['user_id' => $user_id]);
}

这是 profile_details 表

这是前端视图

在此处输入图像描述

请帮助我如何为每个特定用户上传和存储照片。

因此,要上传照片,您至少需要三件事:

  • 可以选择和提交文件的表单
  • controller可以处理这样的请求并在服务器上保存文件
  • 保存上传文件的名称(或完整路径)的数据库字段,以便以后显示或删除它

简而言之,我建议您遵循有关创建新项目上传文件的文档。

但我也可以为您提供一些代码。

1.比方说,我们有这样一个上传文件的表单:

<!-- in such a way you can show already uploaded photo -->
<?php if (!empty($user->photo)): ?>
    <img src="/uploads/<?php echo $user->photo; ?>" alt="<?php echo $user->photo; ?>" width="50">
<?php endif;?>

<!-- pay attention to the hidden field that contains user_id that will be needed during saving the file 
and also to the "multipart" attribute that is required for uploading files.
CodeIgniter automatically can add these attributes using form_open_multipart function -->
<?php echo form_open_multipart('users'); ?>
    <input type="hidden" name="user_id" value="<?php echo $user->id; ?>" />
        <input type="file" name="photo" />
        <input type="submit" name="submit" value="Upload photo" />
</form>

2.然后你应该准备你controller来接收这些数据。 在我的示例中,这是一个带有index方法的Users controller:

/**
 * Index Page for Users controller.
 * It shows a list of existing users for GET method and tries to save user's photo for POST
 */
public function index()
{
    // if we send a form on these method then try to save uploaded file
    if ($this->input->server('REQUEST_METHOD') == 'POST') {
        $this->upload_photo();
    }

    // otherwise, show list of existing users and possible uploading errors
    $this->load->view('users', [
        'errors' => $this->upload_errors,
        'users'  => $this->user_model->get_all()]);
}

/**
 * Method for saving user's profile photo
 */
private function upload_photo()
{
    // get user id from hidden form field
    $user_id = $this->input->post('user_id');

    // delete existing file if it exists
    $existing_photo = $this->user_model->get_photo($user_id)->photo;
    if ($existing_photo && file_exists("./uploads/{$existing_photo}")) {
        unlink("./uploads/{$existing_photo}");
    }

    // "photo" is the name of input element in uploading form
    if (!$this->upload->do_upload('photo')) {
        // save uploading errors to show them on the page
        $this->upload_errors = $this->upload->display_errors();
    }

    // get file name from uploaded data
    $photo = $this->upload->data()['file_name'];

    // save uploaded file name to database for current user
    $this->user_model->update_photo($user_id, $photo);
}

您可以配置用于上传文件的文件夹和其他限制。 本例中的上传文件夹是项目根目录下的uploads

3.在数据库 model 中,您只需要两种简单的方法来获取和更新users表中的photo字段:

/**
 * Class User_model
 */
class User_model extends CI_Model
{
    private $table_name = 'users';

    /**
     * @return mixed
     */
     public function get_all()
     {
         return $this->db->get($this->table_name)->result();
     }

    /**
     * Get filename of user's profile photo
     *
     * @param $user_id
     *
     * @return mixed
     */
    public function get_photo($user_id)
    {
        $this->db->select('photo');

        return $this->db->get_where($this->table_name, ['id' => $user_id])->row();
    }

    /**
    * Update "photo" field for "Users" database table
    *
    * @param $user_id
    * @param $photo
    */
    public function update_photo($user_id, $photo)
    {
        $this->db->update($this->table_name, ['photo' => $photo], ['id' => $user_id]);
    }
}

对于这些操作,需要加载多个库和助手。 您可以在application/config/autoload.php中执行此操作:

$autoload['libraries'] = array('database', 'upload');
$autoload['helper'] = array('form', 'file');

这些基本的东西可以扩展,例如,使用表单验证

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM