How to upload an image to server using jquery ajax function in CodeIgniter.

Hey friends, In this how-to session we are going to learn how to upload an image to the server. For this we need two files.

 A.first  we will create a fileUpload.php in views folder of CI application folder.

 B.second a controller to handle file upload in controllers folder.

1.create a file fileUpload.php.

<html>
<head><title>file upload example<title></head>
<body>
<form id="image_upload_form">
<input type="file" name="userfile" id="userfile">
<input type="submit" name="submit" value="submit">
</form>
<script src="path/to/jquery.js"></script>
<script src="path/to/imageUpload.js"></script>
</html>

2. Now we will create a script file called imageUpload.js.

 

 

$(document).ready(function(){
			$("#image_upload_form").on("submit",function(event){
event.preventDefault();
 if(!$.trim($("#userfile").val()).length)
  {
    
    alert("Please select at least one file");
  
  }
else
{
 var image_form = new FormData($(this));
$.ajax({
    url:'https://www.webtutorial.in/UploadImgController/uploadImgToServer',
    type:'POST',
    processData: false, // important
        contentType: false, // important
    data:image_form,
    
    success:function(data)
    {
var res=$.parseJSON(data);
if(res.response==="ok")
{
      alert("img upload successfull");
}
else
{
alert(data);
}
      
     },
     error:function ( jqXHR,  textStatus,errorThrown)
     {
      alert(errorThrown+'-->textStatus-->'+textStatus+'-->jqXHR-->'+jqXHR);
     } 
    
  });
}
});

 

 Now we have to create a controller UploadImgController.php and put it on controllers folder.

class UploadImgController extends CI_Controller
{

 function __construct()
 {
  parent::__construct();
  $this->load->library("upload");
 }
function fileUploadExample()
{
$this->load->view("fileUpload");
}  
function uploadData($destination,$name)
      {
        if(!is_dir($destination))
        {
        	mkdir($destination, 0777, TRUE);
        }
        $config=array(
       	'upload_path' =>$destination, // path to save file
        'allowed_types' =>"*",        //allowed extentions
        'overwrite' => TRUE,          //overwrite existing file true/false
        'max_size' => "100480000",    //size of file maximum 
        'max_height' => "768",        //if img it's height 
        'max_width' => "1028");       //if img it's width
         $this->upload->initialize($config);
         if(!$this->upload->do_upload($name))
         {
          $error =$this->upload->display_errors();
          $data["response"]=$error;
         } 
         else
         {
          $data["full_path"]=$this->upload->data("full_path");
          $data["file_path"]=$this->upload->data("file_path");
          $data["file_ext"]=$this->upload->data("file_ext");
          $data["response"]="ok";
          
         }
         return $data;
      }
      function uploadImgToServer()
      {
        if(!empty($this->input->post("userfile")))
        {
               $res=$this->uploadData('images/',"userfile");
        }
        else
        {
          $res["response"] = "error";
          $res["message"]  = "Invalid File Input";
        }
        echo json_encode($res);
      }
    }

 Now open your devlopment server where your Ci application is and access  http://yourdomain/UploadImgController/fileUploadExample

when you click on upload button it will upload the file into the server in the desired location and echo back you a response containing all information about image file. 

Other posts