Multiple file upload in codeigniter

Leave a Comment
Hello guy's, Today we gonna look how to upload Multiple file image with codeigniter. After single image upload with codeigniter. We gonna look multiple image upload in codeigniter. First we gonna look multi upload with same controller function after we move that function into helper so we can use somewhere else also. So let's start with controller file

Multi_upload.php (controller)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Multi_upload extends CI_Controller {

 function __construct(){
  parent::__construct();
 }

 public function index()
 {
  $arrData['error'] = '';
  $arrData['content'] = 'multi_image_upload';
  $this->load->view('template',$arrData);
 }

 public function do_multi_upload(){
  if($this->input->post('submit_form')){
   if($_FILES["profile_pic"]["tmp_name"]) {
    $this->do_miltiupload_files('./uploads/', 'M', $_FILES['profile_pic']); // call the function with params
   }
  }
 }

 function do_miltiupload_files($path, $title, $files)
    {   
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['multi_images[]']['name']= $files['name'][$key];
            $_FILES['multi_images[]']['type']= $files['type'][$key];
            $_FILES['multi_images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['multi_images[]']['error']= $files['error'][$key];
            $_FILES['multi_images[]']['size']= $files['size'][$key];
            // here we change file name on run time
            $fileName = $title .'_'. $image;
            $images[] = $fileName;
            $config['file_name'] = $fileName; //new file name

            $this->upload->initialize($config); // load new config setting 

            if ($this->upload->do_upload('multi_images[]')) { // upload file here
             echo "<pre>";
                print_r($this->upload->data());
                // performs your operations
            } else {
                return false;
            }
        }
        return $images;
    }
}
After controller let's create view part
<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo form_open_multipart('multi_upload/do_multi_upload');?>
   <input type="file" name="profile_pic[]" size="20" multiple/>
   <br /><br />
   <input type="submit" value="upload" name="submit_form"/>
</form>

</body>
</html>
now you can hit url on your localhost and try to select multiple file and upload. You get your data and performs your database operations. After uploading image you get this screen
Multiple file upload in codeigniter

0 comments:

Post a Comment

Powered by Blogger.