• Call Us: +92-333-7276335
  • - Mail Us: info@shekztech.com

Plot 1177, Sector 31B - Crossing, Karachi, Sindh

Loading...
Multiple images uploading in codeigniter using jquery and ajax
  • Views: 4.5K
  • Category: Codeigniter
  • Published at: 21 Feb, 2018
  • Updated at: 12 Aug, 2023

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. It's tough to upload files if you talk about Ajax, but CodeIgniter 4 supports various files or images to upload.

You have to be familiar with jquery and Ajax; if you want to upload multiple files in CI, we will upload various 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 for 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

}

 

Shehzad Ahmed

Shehzad Ahmed is a highly qualified expert with a Master of Philosophy in Computer Science and a decade of extensive industry experience. With his impressive track record in web development and computer science, he has not only left an indelible mark on the industry but also made substantial contributions to education. Since , he has created more than eighty exhaustive courses, paving the way for innumerable individuals interested in learning and development. His unparalleled knowledge and innate ability to elucidate complex ideas make him a highly sought-after educator and consultant. Choose Shehzad and take advantage of his exceptional balance of technical expertise and teaching prowess to propel your learning journey or project to new heights.

0 Comment(s)
Write your comment