Upload multiple files in CodeIgniter

30,948

Solution 1

You can Upload any number of Files..

$config['upload_path'] = 'upload/Main_category_product/';
$path=$config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload', $config);

foreach ($_FILES as $fieldname => $fileObject)  //fieldname is the form field name
{
    if (!empty($fileObject['name']))
    {
        $this->upload->initialize($config);
        if (!$this->upload->do_upload($fieldname))
        {
            $errors = $this->upload->display_errors();
            flashMsg($errors);
        }
        else
        {
             // Code After Files Upload Success GOES HERE
        }
    }
}

Solution 2

This is an extension of the CI_Upload class that I modified to upload multiple files, just copy this to the MY_Upload.php file. It also makes the directory as well.

http://pastebin.com/g9J6RxW1

Then all you need to do in the controller function is arrange your files into the an array, where the name of the field and the key are the array keys and the config is the data. In you case something like this:

$project_files['files'][0] = array(
            'upload_path' => './uploads/'.$projectName.'/',
            'max_size' => 0,
            'allowed_types' => 'xml|etl',
            'overwrite' => TRUE,
            'remove_spaces' => TRUE,
        );
$project_files['files'][1] = array(
            'upload_path' => './uploads/'.$projectName.'/',
            'max_size' => 0,
            'allowed_types' => 'xml|etl',
            'overwrite' => TRUE,
            'remove_spaces' => TRUE,
        );

IF all the files configs are the same just make a for loop to set this up, it will also take 'named keys', ie. $project_files['files']['file_key'].

then just call:

 if($this->upload->upload_files($project_files)){/*all files uploaded successfully*/}

Solution 3

I can't comment yet because of my reputation level but Zoom made a comment under the accepted answer about the $fieldname variable being an array which caused an error. I had the same issue with that answer and found out that it was because I had appended all my file input names on the form with [] which made php pick up the those inputs as an array variable. To resolve that issue just give each file input a unique name instead of making it a PHP array. After I did that, the issue went away for me and the accepted answer worked like a charm. Just thought I'd pass the info along for anyone else who stumbles across this issue.

Share:
30,948
cycero
Author by

cycero

Updated on April 11, 2020

Comments

  • cycero
    cycero about 4 years

    In my CodeIgniter project I'm uploading files during the project creation. Here's the uploading function:

    function uploadFiles(){
    
         $this->load->library('upload');  
         $error = 0;    
         $projectName = $_POST['projectname'];
         mkdir('./uploads/'.$projectName);
    
         for($i=0; $i<count($_FILES); $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];
    
           $config['upload_path']   = './uploads/'.$projectName;
           $config['allowed_types'] = 'xml|etl';
           $config['max_size']      = '0';
           $config['overwrite']     = TRUE;
    
          $this->upload->initialize($config);
    
          if($this->upload->do_upload())
          {
            $error += 0;
          }else{
            $error += 1;
          }
         }
    
         if($error > 0){ return FALSE; }else{ return TRUE; }
    
    }
    

    And I call this function in the create_project function like this:

    public function create_project() {
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('projectname', 'Project name', 'required');
    
        $this->form_validation->set_message('required', 'This is an obligatory field');
    
        if($this->form_validation->run() == FALSE) {
            $this->load->view('project_creation_view');
        } else {
            $this->load->model('Project_management_model');
            $this->Project_management_model->create_project();
            $this->uploadFiles();
        }
    }
    

    However this does not do anything. The files are not being uploaded. Even an empty directory is not being created. Could anybody help me to find the error?

    Thanks.

  • jason
    jason over 10 years
    Is there a setting for the number of files? I was only able to upload 20 with my codeigniter code and its not much different than this.
  • zoom
    zoom about 8 years
    It gave me error is_uploaded_file() expects parameter 1 to be string, array given, as I tried to debug, $fieldname is an array.
  • ankit suthar
    ankit suthar over 7 years
    I tried your code I get one issue with this code. If user upload text file or any other nonimage file with the images (textfile + images) then it uploads some of them and returns the error of file type. Ideally, it may not allow any single image if one of them is not an image. Any help over this? @srbhbarot
  • TARKUS
    TARKUS about 7 years
    What do you mean give each file input a unique name? There is a difference between using a single <input type="file" name="files[]" multiple="multiple" /> and using multiple input field lines. With the single input field, you can select multiple files from the file browser window. With multiple input fields you can only choose one file at a time, and I think that degrades the select multiple files feature, but I guess it works. Maybe you could explain a little more what you mean?
  • TARKUS
    TARKUS about 7 years
    Also, I am using the name='files[]' too, so I know what you're driving at. In the Ajax call I loop through the files[] like this: formData.append('date',document.getElementById('date').value‌​); var ins = document.getElementById('files').files.length; for (var x = 0; x < ins; x++) { formData.append("files[]", document.getElementById('files').files[x]); } In the Controller, this produces a $_FILES array, which you can check with echo "<pre>"; print_r($_FILES); echo "</pre>"; Still, the above accepted answer isn't working for me, so I'm still doing something wrong. :/
  • TARKUS
    TARKUS about 7 years
    @jason I can only upload a max of 20 files, too. Would like a solution.