0

I am trying to upload multiple images using single input in codeigniter with ajax, here's my code. HTML:

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

AJAX:

$("#addItems").on("submit",function(even)
{
    even.preventDefault();
    $.ajax({
        url         : base_url+"dashboard/insert_item",
        type        : "POST",
        data        : new FormData(this),
        cache       : false,
        contentType : false,
        processData : false,
        success     : function(data)
        {
            data = JSON.parse(data);
            if(data.code == 201)
            {
                $.toaster({ title : 'Message', priority : 'success', message : data.record });
            }
            else
            {
                $.toaster({ title : 'Error', priority : 'danger', message : data.errors });
            }
        }
    });
});

My Controller Code:

if ( !empty($_FILES) ) {
    $this->load->library('upload');

    //Configure upload.
    $this->upload->initialize(array(
        "allowed_types" => "gif|jpg|png|jpeg",
        "upload_path"   => "./uploads/"
    ));

    //Perform upload.
    if($this->upload->do_upload("files")) 
    {
        $uploaded = $this->upload->data();
        echo '<pre>';
        var_export($uploaded);
        echo '</pre>';
    }
    else
    {
        die('UPLOAD FAILED');
    } 
    // $response = makeResponse(201,'success','','Item Added Successfully!');
}

The issue is that i am getting only one image in new FormData, i have tried every thing but still getting one image not multiple images in my FormData Object. How can i get all images value in new FormData object ? is there any way

Nick
  • 565
  • 4
  • 19

1 Answers1

1

You can loop through file and send it to server.

let files = [];
let inputFile = $('#file');
 inputFile.change(function() {
    let newFiles = []; 
    for(let index = 0; index < inputFile[0].files.length; index++) {
      let file = inputFile[0].files[index];
      newFiles.push(file);
      files.push(file);
    }



  console.log('files all files', files);


  var formData = new FormData();
                files.forEach(file => {
                  formData.append('attachment[]', file);
                });

  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="files[]" id="file" multiple />
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37