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>

0 comments:

Post a Comment