Nishita Patel Nishita Patel - 5 months ago 36
Ajax Question

how to upload image with ajax and codeigniter where my CI is IN var/www/html

In html file upload is in form like this

<form method="post" action="" enctype = "multipart/form-data" ><label> File Input: </label><input type = "file" name = "userfile" id="userfile"><a href = "http://localhost/upload_img/index.php/upload/do_upload" >Submit </a></form>


in my controller:

<?php class Upload extends CI_Controller {
public function index(){
$this->load->view('upload_view');
}
public function do_upload(){
$config = array(
'upload_path' => "http://localhost/upload_img/index.php/uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf"
);
//print_r($config);
$this->load->library('upload', $config);
if($this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r( $error);
}
}
}

Answer

Changes

  1. <fomr> action filed is set
  2. Submitting data with <input type="submit"
  3. upload_path Modified

Try this

In View

<form method="post" action="<?php echo base_url() ;?>index.php/upload/do_upload" enctype = "multipart/form-data" >
      <label> File Input: </label>
      <input type="file" name="userfile" id="userfile">
      <input type="submit" name="submit" value="Upload" />
</form>

In Controller

class Upload extends CI_Controller {

   public function index(){
      $this->load->view('upload_view');
   }

   public function do_upload()
   {

       $config = array(
            'upload_path' => "./uploads/",
            'allowed_types' => "gif|jpg|png|jpeg|pdf|doc|docx"
        );

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

        if(!$this->upload->do_upload('userfile'))
        {
            $error = array('error' => $this->upload->display_errors());
            print_r( $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            print_r($data);
        }
    }
}

If you using Ubuntu OS. Then give 777 permission to upload folder.

Comments