Tuesday 14 March 2017

Upload Multiple Files or Images in Codeigniter using Ajax JQuery



We have received many web tutorial request on How can we upload multiple images file without using form in Codeigniter by using Ajax Jquery. So We have this simple web tutorial on multiple file upload in Codeigniter framework by using Ajax with Jquery without refreshing of web page. For making this web tutorial we have use Codeigniter Framework with PHP Ajax and JQuery. By using this code you can upload multiple image file with preview in Codeingiter Framework by using Jquery Ajax and PHP.


class Upload_multiple extends CI_Controller {
 
 function index()
 {
  $this->load->view("upload_multiple");
 }


In this web tutorial we have create multiple_upload.php file in View folder and from controller we have load this file in index() function of Upload_multiple.php file controller. After loading this file from controller then after in that file we have use only simple input file tag with multiple attribute for select multiple file from local source. We have not use any HTML form and we have not submit form data to server. Here when we have select multiple file from our computer then it will be directly uploaded to specified destination. Here we have write jquery code on input file element change event. So when we have select multiple file then it will directly uploaded to server.


<div class="col-md-6" align="right">
  <label>Select Multiple Files</label>
 </div>
 <div class="col-md-6">
  <input type="file" name="files" id="files" multiple />
 </div>
 <div style="clear:both"></div>
 <br />
 <br />
 <div id="uploaded_images"></div>



$('#files').change(function(){
  var files = $('#files')[0].files;
  var error = '';
  var form_data = new FormData();
  for(var count = 0; count<files.length; count++)
  {
   var name = files[count].name;
   var extension = name.split('.').pop().toLowerCase();
   if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
   {
    error += "Invalid " + count + " Image File"
   }
   else
   {
    form_data.append("files[]", files[count]);
   }
  }
  if(error == '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>upload_multiple/upload", //base_url() return http://localhost/tutorial/codeigniter/
    method:"POST",
    data:form_data,
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function()
    {
     $('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
    },
    success:function(data)
    {
     $('#uploaded_images').html(data);
     $('#files').val('');
    }
   })
  }
  else
  {
   alert(error);
  }
 });


For sending selecting file to server, first we have create on FormData() object and in that object we have append selected file property into that FormData() object variable in Jquery code. After appending selected file property into form data object variable then after we have use Ajax request and via Ajax request we have send form object variable data to server. This way we have send multiple file property server.


function upload()
 {
  sleep(3);
  if($_FILES["files"]["name"] != '')
  {
   $output = '';
   $config["upload_path"] = './upload/';
   $config["allowed_types"] = 'gif|jpg|png';
   $this->load->library('upload', $config);
   $this->upload->initialize($config);
   for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
   {
    $_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
    $_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
    $_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
    $_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
    $_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
    if($this->upload->do_upload('file'))
    {
     $data = $this->upload->data();
     $output .= '
     <div class="col-md-3">
      <img src="'.base_url().'upload/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
     </div>
     ';
    }
   }
   echo $output;   
  }
 }


At server side code we have go to Upload_multiple.php in controller folder, in this first we have define configuration for load upload library. After defining configuration for upload library we have load upload library and then after we have initialize upload library. Then after we have fetch single file property from multiple files and upload one by one to specified destination by using Codeigniter Upload library function do_upload().






Source Code


Controllers - Upload_multiple.php



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload_multiple extends CI_Controller {
 
 function index()
 {
  $this->load->view("upload_multiple");
 }

 function upload()
 {
  sleep(3);
  if($_FILES["files"]["name"] != '')
  {
   $output = '';
   $config["upload_path"] = './upload/';
   $config["allowed_types"] = 'gif|jpg|png';
   $this->load->library('upload', $config);
   $this->upload->initialize($config);
   for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
   {
    $_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
    $_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
    $_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
    $_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
    $_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
    if($this->upload->do_upload('file'))
    {
     $data = $this->upload->data();
     $output .= '
     <div class="col-md-3">
      <img src="'.base_url().'upload/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
     </div>
     ';
    }
   }
   echo $output;   
  }
 }
}


Views - upload_multiple.php



<html>
<head>
    <title>Upload Multiple Files in Codeigniter using Ajax JQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
 <br /><br /><br />
 <h3 align="center">Upload Multiple Files in Codeigniter using Ajax JQuery</h3><br />
 
 <div class="col-md-6" align="right">
  <label>Select Multiple Files</label>
 </div>
 <div class="col-md-6">
  <input type="file" name="files" id="files" multiple />
 </div>
 <div style="clear:both"></div>
 <br />
 <br />
 <div id="uploaded_images"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
 $('#files').change(function(){
  var files = $('#files')[0].files;
  var error = '';
  var form_data = new FormData();
  for(var count = 0; count<files.length; count++)
  {
   var name = files[count].name;
   var extension = name.split('.').pop().toLowerCase();
   if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
   {
    error += "Invalid " + count + " Image File"
   }
   else
   {
    form_data.append("files[]", files[count]);
   }
  }
  if(error == '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>upload_multiple/upload", //base_url() return http://localhost/tutorial/codeigniter/
    method:"POST",
    data:form_data,
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function()
    {
     $('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
    },
    success:function(data)
    {
     $('#uploaded_images').html(data);
     $('#files').val('');
    }
   })
  }
  else
  {
   alert(error);
  }
 });
});
</script>

7 comments:

  1. me not working your example, charge and not upload files images

    ReplyDelete
  2. Here you have not written form tag.Is it okay with it ?

    ReplyDelete
  3. please do a project combining all lesson because you gave me alot of confidence on codeigniter.I appreciate

    ReplyDelete
  4. sir how to saves the information eg name into database? please help me

    ReplyDelete
  5. This is a good snippet, clarifies many issues for me. I haven't tried it yet as i am experimenting on other models.

    However, reading through i think there may be a subtle error in the ajax script.
    Look at this code:
    form_data.append("files[]", files[count]);

    My comments as follows.

    // This does not seem to be correct, since its will return
    // 'files[]', filename0
    // 'files[]', filename1
    // 'files[]', filename2 etc.
    // However we want
    // 'files[0]', filename0
    // 'files[1]', filename1
    // 'files[2]', filename2 etc.
    // SO form_data.append("files[]", files[count]) should be
    // form_data.append("files[" . count . "]", files[count])
    // We can now regenerate the $_FILES as illustrated on the PHP side.

    That said, why the regeneration on the PHP side be done at the ajax side? Just a thought.


    ReplyDelete
  6. Hlo Sir, First of all thank you for provide a best tutorial on how to upload multiple image by jquery.

    Now My problem is that when we upload image then it is going to upload successfully but images is not displayed after uploading like your video tutorial? please find any solution to my problem.

    I am using your code line by line. I haven't edited anything in your code

    ReplyDelete
  7. Sir after uploaded image it does not return to the success function why?

    ReplyDelete