Multiple images uploading in codeigniter using jquery and ajax

multiple images uploading in codeigniter using jquery and ajax

We know very well CodeIgniter 3 only supports single file uploading using the upload library. Hence, it’s hard to upload multiple files in CodeIgniter. If you are talking about ajax, it’s tough to upload files, but CodeIgniter 4 is now supporting the various files or images to upload.

You have to familiar with jquery and ajax; if you want to upload multiple files in CI, we are going to upload various files OR images using jquery in CodeIgniter.

Step 1: Create your view named files.php

 

<input class="dinon" type="file" id="multiFiles" name="files[]" multiple="multiple"/>

 

Step:2 Add jquery code inside your script files, i.e., custom.js 

 

$('#multiFiles').on('change', function () {
        var form_data = new FormData();
        var ins = document.getElementById('multiFiles').files.length;
        for (var x = 0; x < ins; x++) {
            form_data.append("files[]", document.getElementById('multiFiles').files[x]);
        }

        $.ajax({
            url: "http://YourDomainName/carList/myupload", 
            dataType: 'text',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (response) {
            var obje = JSON.parse(response);
            if(obje.return == false){
                    $('.erimgs').text(obje.message);// display error
                }
            else if(obje.length >  0){
             var table = "";/variable to save all images
                //obje.length;
                for (var loop = 0; loop < obje.length; loop++) //
                  {  
                            table+='src="domainName/FolderName/'+obje[i].fileName+'" ';
                           //adding all images in the same variable
                   }
                 $('.llaimg').html(table);

            }
            else{
                 $('.erimgs').text(obje.message);// display error
               }
            },
            error: function (response) {
                $('#msg').html(response); // display error response from the server
            }
        });//ajax here

    });//selector here

 

Step 3: Create a method of your controller

 

public function myupload()
{
    $this->load->library('upload');//loading the library
    $imagePath = realpath(APPPATH . '../assets/images/carImages');//this is your real path APPPATH means you are at the application folder
    $number_of_files_uploaded = count($_FILES['files']['name']);

    if ($number_of_files_uploaded > 5){ // checking how many images your user/client can upload
        $carImages['return'] = false;
        $carImages['message'] = "You can upload 5 Images";
        echo json_encode($carImages);
    }
    else{
        for ($i = 0; $i <  $number_of_files_uploaded; $i++) {
            $_FILES['userfile']['name']     = $_FILES['files']['name'][$i];
            $_FILES['userfile']['type']     = $_FILES['files']['type'][$i];
            $_FILES['userfile']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
            $_FILES['userfile']['error']    = $_FILES['files']['error'][$i];
            $_FILES['userfile']['size']     = $_FILES['files']['size'][$i];
            //configuration for upload your images
            $config = array(
                'file_name'     => random_string('alnum', 16),
                'allowed_types' => 'jpg|jpeg|png|gif',
                'max_size'      => 3000,
                'overwrite'     => FALSE,
                'upload_path'
                =>$imagePath
            );
            $this->upload->initialize($config);
            $errCount = 0;//counting errrs
            if (!$this->upload->do_upload())
            {
                $error = array('error' => $this->upload->display_errors());
                $carImages[] = array(
                    'errors'=> $error
                );//saving arrors in the array
            }
            else
            {
                $filename = $this->upload->data();
                $carImages[] = array(
                    'fileName'=>$filename['file_name'],
                    'watermark'=> $this->createWatermark($filename['file_name'])
                );
            }//if file uploaded
            
        }//for loop ends here
        echo json_encode($carImages);//sending the data to the jquery/ajax or you can save the files name inside your database.
    }//else

}
shakzee
administrator
My Name is Shehzad Ahmed and I am a full-time developer with over 7+ years of experience. In that time, I’ve worked as a developer with many big and small firms and was teaching web design and development skills to many keen learners and by the time passes I’ve found a great passion and potential on myself as a teacher on this particular field and now I am a full-time teacher and working as a freelancer.

Comments

  • melati
    July 26, 2018

    how about, i have two field and i two button uploading in codeigniter using jquery and ajax ?
    can you tell me!! please , thank you

    • shakzee
      July 25, 2018

      I am not getting your point please explain further.

  • SUMIT KUMAR GUPTA
    November 2, 2018

    If you provide code for anything then provide full code because beginners can’t understand where is used which class name and where is used which Id name. So please when you publish new post on any code then provide full code.

    • shakzee
      November 7, 2018

      Thank you for you comment i will upload the projects files next time. 🙂

  • Elvis
    January 16, 2019

    Thank you. but how can i send uploaded images path to database so i can call them back

    • shakzee
      January 17, 2019

      Its very simple outside of the for loop call your model i.e your model is myModel and your method is addImages now.
      $this->myModel->addImages($carImages);

      Now go your model(myModel) and add this method

      public function addImages($imgages)
      {
      return $this->db->insert_batch(‘yourTablesName’,$imgages);//this is the insert_batch() method to insert multiple recoreds in a table.
      }

Leave a Reply

Your email address will not be published. Required fields are marked *