简体   繁体   中英

Image Upload in CodeIgniter using PHP

I have a view where the user can edit his details.

View

<form class="form-horizontal" method ="post" action="<?php echo site_url('studentDashboardController/saveUserDetails');?>">
<?php echo form_open('studentDashboardController/saveUserDetails'); ?>
<?php echo $this->session->flashdata('msg'); ?>
<fieldset>

    <!-- Form Name -->
    <legend>User Details</legend>

    <!-- Text input-->
    <div class="form-group">
        <label class="col-md-4 control-label" for="name">Full Name</label>
        <div class="col-md-8">
            <input id="name" name="name" type="text" class="form-control input-md" value="<?php foreach($details as $detail){?><?php echo $detail->name?><?php }?>">
        </div>
    </div>

    <!-- Text input-->
    <div class="form-group">
        <label class="col-md-4 control-label" for="dob">Date of Birth</label>
        <div class="col-md-8">
            <input id="dob" name="dob" type="text" placeholder="" class="form-control input-md" value="">
        </div>
    </div>

    ...

    <!-- File Button -->
    <div class="form-group">
        <label class="col-md-4 control-label" for="userfile">Upload Profile Picture</label>
        <div class="col-md-4">
            <input id="userfile" name="userfile" class="input-file" type="file">
        </div>
    </div>

    <!-- Button -->
    <div class="form-group">
        <label class="col-md-4 control-label" for="submit"></label>
        <div class="col-md-4">
            <button id="submit" name="submit" type="submit" class="btn btn-primary">Save Changes</button>
        </div>
    </div>

Controller

public function  saveUserDetails()
{
    if (isset($this->session->userdata['logged_in']))
    {
        $uid = ($this->session->userdata['logged_in']['userId']);

        $data['notifyCount']=  $this->notifications->getUnreadNotification($uid);
        $data['title']=  $this->notifications->getUnreadNotificationTitle($uid);
        $data['notifyCount']=  $this->notifications->getUnreadNotification($uid);
        $data['users'] = $this->user->getUserNames();

        $config['upload_path'] = './assets/img/taro/profilePictures/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '10000';
        $config['max_width']  = '5000';
        $config['max_height']  = '3000';
        $this->load->library('upload', $config);

        $this->upload->do_upload();
        $upload_data = $this->upload->data();

        $msg = $this->studentprofileModel->saveUserDetails($uid,$this->input->post());
        $msgText = $msg['msg'];
        $msgType = $msg['type'];
        //Loading View
        if($msgType == "danger")
        {
            $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">'.$msgText.'</div>');
        }
        else
        {
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-center">'.$msgText.'</div>');
        }

        redirect(base_url('index.php/studentDashboardController/loadGeneralProfilePage'));
    }
    else
    {
        $this->load->view('login/loginView');
    }
}

What I need to do is to first save the user details collected via the form by calling the studentprofileModel's saveUserDetails method. In this method I need to send the uploaded image's name so that I can store the image path in the db table's image field. And I need to upload the image to the assets folder's subdirectory taro as well.

I have done the following and the data from the form fields get updated in the DB. But the image file is not uploaded.

Any suggestions in this regard will be highly appreciated

My first guess, before further tests, would be to add the enctype="multipart/form-data" attribute to your <form> tag, as it specifies how the form-data should be encoded when submitting it to the server and the multipart/form-data is required when the form includes any <input type="file"> .

You can read more about this here .


Update 2:

Actually, it seems you may have two form tags opened? one from <form> and another one from form_open() function CI provides? If so, use only one of them.

If you choose to do in HTML:

<form class="form-horizontal" method ="post" action="<?php echo site_url('studentDashboardController/saveUserDetails');?>" enctype="multipart/form-data">

If you choose to use CI's functions, there's two ways: form_open and form_open_multipart (which is exactly like form_open but it adds automatically the multipart thing)

form_open('studentDashboardController/saveUserDetails', array('enctype' => "multipart/form-data"))

or

form_open_multipart('studentDashboardController/saveUserDetails')


Update 3:

  • Make sure that the folder where the image will be uploaded to have enough permissions;

  • Pass the absolute path in here $config['upload_path'] = './assets/img/taro/profilePictures/' instead of the relative one

  • Also, change this $this->upload->do_upload(); to $this->upload->do_upload('userfile');

Let us know the results :)

You can add this code in your controller "function saveUserDetails()"

   public function  saveUserDetails()
  {
      if (isset($this->session->userdata['logged_in']))
      {
         $uid = ($this->session->userdata['logged_in']['userId']);
         $post_data = $this->input->post();
       if($_FILES['image']['name'])
      {
          //load upload library
          $this->load->library('upload');

          // Specify configuration for File 
          $config['upload_path'] = './assets/img/taro/profilePictures/';
          $config['allowed_types'] = 'gif|jpg|png';
          $config['max_size'] = '10000';
          $config['max_width']  = '5000';
          $config['max_height']  = '3000';
          $this->upload->initialize($config);

          if ($this->upload->do_upload('image')){
               $image_data = $this->upload->data();
              $post_data['image'] = $image_data['file_name'];
          }
          else{
              $error = $this->upload->display_errors();
         }
       }

        $msg = $this->studentprofileModel->saveUserDetails($uid,$post_data);
        $msgText = $msg['msg'];
        $msgType = $msg['type'];
        .....
   }

Don't forget give permision to image folder.

I hope it will work for you!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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