0

I am not able to upload any images after second input. I can only upload the first input. The inputs are created dynamically when another input value is added. Below is the code:

\\ jquery //
function storeupdate(){
$.ajax({
  type:"POST",
  url:"<?php echo base_url(); ?>updatestore",
  data:$("#mainstore").serialize(),
  success: function(response){
    var data = new FormData();
    input = document.getElementById('file');
      for(var i = 0; i < input.files.length; i++)
      {
        data.append('images[]', document.getElementById('file').files[i]);
      }
    $.ajax({
        type: 'POST',
        url: '<?php echo base_url(); ?>storeupload',
        cache: false,
        contentType: false,
        processData: false,
        data : data,
        success: function(result){
            console.log(result);
        },
        error: function(err){
            console.log(err);
        }
    });
    swal('Successful!', 'Data has been saved!', 'success');
    //window.location.reload();
  },
  error: function() {
    swal("Oops", "We couldn't connect to the server!", "error");
  }
 });
 return false;
 };


\\ view // 
<input type="file" name="images[]" id="file" class="file" accept="image/*;capture=camera" multiple="multiple" />
<button type="button" class="btn btn-success save" id="save" name="save" onclick="storeupdate();" disabled>Save</button>


\\ controller //
public function storeupload()
{
$files= $_FILES;
$cpt = count ($_FILES['images']['name']);
for($i = 0; $i < $cpt; $i ++) {

    $_FILES['images']['name'] = $files['images']['name'][$i];
    $_FILES['images']['type'] = $files['images']['type'][$i];
    $_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
    $_FILES['images']['error'] = $files['images']['error'][$i];
    $_FILES['images']['size'] = $files['images']['size'][$i];

    $this->upload->initialize ( $this->set_upload_options1() );
    $this->upload->do_upload("images");
    $fileName = $_FILES['images']['name'];
    $images[] = $fileName;
}

}
halfer
  • 19,824
  • 17
  • 99
  • 186
user2531242
  • 1
  • 1
  • 5

2 Answers2

2

I made and tested a little sample of code so that you can see what's wrong. You have a few things wrong. First thing I would recommend is actually using jQuery. Your code is obviously using jQuery, but you have all kinds of vanilla JS that can be simplified:

$(document).ready(function(){

    $('#save').on('click', function(){
        var fileInput = $('#file_input')[0];
        if( fileInput.files.length > 0 ){
            var formData = new FormData();
            $.each(fileInput.files, function(k,file){
                formData.append('images[]', file);
            });
            $.ajax({
                method: 'post',
                url:"/multi_uploader/process",
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function(response){
                    console.log(response);
                }
            });
        }else{
            console.log('No Files Selected');
        }
    });

});

Notice that I hard coded in the ajax URL. The controller I used for testing was named Multi_uploader.php.

Next is that in your controller when you loop through the $_FILES, you need to convert that over to "userfile". This is very important if you plan to use the CodeIgniter upload class:

public function process()
{
    $F = array();

    $count_uploaded_files = count( $_FILES['images']['name'] );

    $files = $_FILES;
    for( $i = 0; $i < $count_uploaded_files; $i++ )
    {
        $_FILES['userfile'] = [
            'name'     => $files['images']['name'][$i],
            'type'     => $files['images']['type'][$i],
            'tmp_name' => $files['images']['tmp_name'][$i],
            'error'    => $files['images']['error'][$i],
            'size'     => $files['images']['size'][$i]
        ];

        $F[] = $_FILES['userfile'];

        // Here is where you do your CodeIgniter upload ...
    }

    echo json_encode($F);
}

This is the view that I used for testing:

<!doctype html>
<html>
<head>
    <title>Multi Uploader</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="/js/multi_uploader.js"></script>
</head>
<body>
    <form>
        <input type="file" name="images[]" id="file_input" multiple />
        <button type="button" id="save">Upload</button>
    </form>
</body>
</html>

Finally, just to prove that the files were uploaded to the controller, and that I could use them with CodeIgniter, I send the ajax response as a json encoded array, and display it in the console. See the code comment where you would put your CodeIgniter upload code.

UPDATE (to show what to do with multiple file inputs) ---

If you want to have multiple file inputs, then that obviously changes your HTML and JS a bit. In that case, your HTML would have the multiple inputs:

<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />

And your javascript needs to change to loop through each input:

$(document).ready(function(){
    $('#save').on('click', function(){
        var fileInputs = $('.file_input');
        var formData = new FormData();
        $.each(fileInputs, function(i,fileInput){
            if( fileInput.files.length > 0 ){
                $.each(fileInput.files, function(k,file){
                    formData.append('images[]', file);
                });
            }
        });
        $.ajax({
            method: 'post',
            url:"/multi_uploader/process",
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function(response){
                console.log(response);
            }
        });
    });
});

A little more info about your comment regarding adding the details to your database ---

When you do an upload with CodeIgniter, there is a provided upload summary:

$summary = $this->upload->data();

This is an array of data that ends up looking like this:

$summary = array(
    'file_name'     => 'mypic.jpg',
    'file_type'     => 'image/jpeg',
    'file_path'     => '/path/to/your/upload/',
    'full_path'     => '/path/to/your/upload/jpg.jpg',
    'raw_name'      => 'mypic',
    'orig_name'     => 'mypic.jpg',
    'client_name'   => 'mypic.jpg',
    'file_ext'      => '.jpg',
    'file_size'     => 22.2
    'is_image'      => 1
    'image_width'   => 800
    'image_height'  => 600
    'image_type'    => 'jpeg',
    'image_size_str' => 'width="800" height="200"'
);

So all you would have to do to add a record to your database is this after each upload:

$summary = $this->upload->data();

$this->db->insert('storefiles', array(
    'Store_ID'  => $_POST['storeid'],
    'File_Name' => $summary['file_name'], 
    'Created'   => date('Y-m-d h:i:s'), 
    'Modified'  => date('Y-m-d h:i:s')
));

It's pretty easy to see that you could store a lot more than just the filename.

Brian Gottier
  • 4,522
  • 3
  • 21
  • 37
  • Thanks a bunch. I am able to upload each image to the folder. Now I am not able to add to my database. Here is the code: $filename = implode(',',$F); $this->Stock->upload_image($filename); \\ model // function upload_image($filename) { if($filename!='' ){ $filename1 = explode(',',$filename); foreach($filename1 as $file){ $file_data = array( 'Store_ID' => $_POST['storeid'],'File_Name' => $file, 'Created' => date('Y-m-d h:i:s'), 'Modified' => date('Y-m-d h:i:s')); $this->db->insert('storefiles', $file_data); } }} – user2531242 Oct 09 '17 at 08:32
  • Thanks Brian for all the help very appreciated. I am getting an error, Array to string conversion. Here is my code: $filename = implode(',',$F); $this->Stock->upload_image($filename); \\ model // function upload_image($summary) {$this->db->insert('storefiles', array( 'Store_ID' => $_POST['storeid'], 'File_Name' => $summary['file_name'], 'Created' => date('Y-m-d h:i:s'), 'Modified' => date('Y-m-d h:i:s') )); } – user2531242 Oct 09 '17 at 15:29
  • I can't tell exactly what's going on, but that error is common. It's just that the code is expecting an array at some point, and you're providing an array. You might check the line number of the error, and it should give you some clues how to proceed. Also, it's extremely hard to read your code here in the comments. You should start a new Stack Overflow question if you need more help. – Brian Gottier Oct 09 '17 at 18:10
  • I manage to add the file_name to the database. You are right there is more we can do with the info. The images are part of a bigger dynamic form where based on quantity the input fields show for example 2 qty will show 2 input type file field and input type text field. Currently, the setup is that there is a sperate table for storing image name with storeid. Each form has it own unique storeid where the storeid is used to retrieve the images. I am able to store dynamic input type field in main table in an array eg. ["88976543","22345765"]. I wish to store the same in images file_name. – user2531242 Oct 10 '17 at 02:53
0

I know this question is old, but for people like me who encounter this error: is_uploaded_file() expects parameter 1 to be string, array given after using the Code Igniter file upload library within the loop like so:

for ( $i = 0; $i < count($var); $i++ )
{
    // other codes here

    // Do codeigniter upload
    $this->upload->do_upload('images');
}

What you can do is to not put any params in the do_upload() function. Like so:

$this->upload->do_upload();
Samuel Asor
  • 480
  • 8
  • 25