Upload Multiple Images in Codeigniter Using Ajax

Codeigniter 3 Ajax Multiple Images Upload – We will share with how to upload multiple images using ajax into database & folder. We will upload multiple images using ajax and jquery. We will upload the multiple images using jquery ajax without page refresh and reload.

In this codeigniter multiple ajax image upload tutorial with live preview. We will upload multiple images into database and folder. Before upload multiple images in database and folder we will show preview of the multiple images.

In every web development, we need to upload multiple images into database without refreshing and reloading the whole web page. In this codeigniter tutorial you will learn simple ajax multiple images upload step by step.

Codeigniter Ajax Multiple Image Upload

Contents

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ and also rename your project folder name to demo.

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo';

Create Database With Table

In this step, we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo . After successfully create a database, you can use the below sql query for creating a table in your database.

CREATE TABLE IF NOT EXISTS images(
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

Setup Database Credentials

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Create Controller

Now we need to create a controller name Ajax.php. In this controller we will create some method/function name multipleImage() and multipleImageStore() for showing and storing a multiple images into database and folder.

Note:- Before upload multiple images go to your project root directory and create a folder name “uploads” where we will store a image.

<?php
class Ajax extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->helper('form');
        $this->load->database();
    }

  public function multipleImage()
  {
    $this->load->view('multiple-image');
  }

  public function multipleImageStore()
  {

      $countfiles = count($_FILES['files']['name']);

      for($i=0;$i<$countfiles;$i++){

        if(!empty($_FILES['files']['name'][$i])){

          // Define new $_FILES array - $_FILES['file']
          $_FILES['file']['name'] = $_FILES['files']['name'][$i];
          $_FILES['file']['type'] = $_FILES['files']['type'][$i];
          $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
          $_FILES['file']['error'] = $_FILES['files']['error'][$i];
          $_FILES['file']['size'] = $_FILES['files']['size'][$i];

          // Set preference
          $config['upload_path'] = './uploads/';
          $config['allowed_types'] = 'jpg|jpeg|png|gif';
          $config['max_size'] = '5000'; // max_size in kb
          $config['file_name'] = $_FILES['files']['name'][$i];

          //Load upload library
          $this->load->library('upload',$config);
          $arr = array('msg' => 'something went wrong', 'success' => false);
          // File upload
          if($this->upload->do_upload('file')){

           $data = $this->upload->data();
           $insert['name'] = $data['file_name'];
           $this->db->insert('images',$insert);
           $get = $this->db->insert_id();
          $arr = array('msg' => 'Image has been uploaded successfully', 'success' => true);

          }
        }

      }
      echo json_encode($arr);

  }

}

Create Views

Now we need to create view for showing multiple images upload form, so go to application/views/ and here create one view name multiple-image.php . After create this view put the below html in view.

<!DOCTYPE html>
<html>
<head>
  <title>Upload Multiple Images in Codeigniter Using Ajax</title>
</head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" >
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<style type="text/css">
.thumb{
  margin: 24px 5px 20px 0;
  width: 150px;
  float: left;
}
#blah {
  border: 2px solid;
  display: block;
  background-color: white;
  border-radius: 5px;
}
</style>
<body>
  <?php $this->load->view('layout/header',array('heading' => 'Upload Multiple Images in Codeigniter Using Ajax')); ?>
 <div  class="container">
  <div id="divMsg" class="alert alert-success" style="display: none">
   <span id="msg"></span>
  </div>
  <br><br>
   <div class="row" id="blah">
    <form method="post" id="upload_form" enctype="multipart/form-data">
    <div class="form-control col-md-12">
      <input type="file" id="image_file" multiple="multiple" />
      <br>
      <div id="uploadPreview"></div>
   </div></br></br><br>
   <div class="form-group col-md-6">
     <button>Submit</button>
   </div>
  </form>
   </div>
 </div>
</body>
</html>

After create a multiple-image.php file and put the above html, Next we need to put the ajax image sending code to the above file so put the below code in multiple-image.php file after closing a body tag.

<script type="text/javascript">

 $(document).ready(function(){
      $('#upload_form').on('submit', function(e){
           e.preventDefault();
           if($('#image_file').val() == '')
           {
                alert("Please Select the File");
           }
           else
           {
              var form_data = new FormData();
              var ins = document.getElementById('image_file').files.length;
              for (var x = 0; x < ins; x++) {
                  form_data.append("files[]", document.getElementById('image_file').files[x]);
              }
                $.ajax({
                     url:"<?php echo base_url(); ?>ajax/multipleImageStore",
                     method:"POST",
                     data:form_data,
                     contentType: false,
                     cache: false,
                     processData:false,
                     dataType: "json",
                     success:function(res)
                     {
                        console.log(res.success);
                        if(res.success == true){
                         $('#image_file').val('');
                         $('#uploadPreview').html('');
                         $('#msg').html(res.msg);
                         $('#divMsg').show();
                        }
                        else if(res.success == false){
                          $('#msg').html(res.msg);
                          $('#divMsg').show();
                        }
                        setTimeout(function(){
                         $('#msg').html('');
                         $('#divMsg').hide();
                        }, 3000);
                     }
                });
           }
      });
 });
// var url = window.URL || window.webkitURL; // alternate use

function readImage(file) {
  var reader = new FileReader();
  var image  = new Image();

  reader.readAsDataURL(file);
  reader.onload = function(_file) {
    image.src = _file.target.result; // url.createObjectURL(file);
    image.onload = function() {
      var w = this.width,
          h = this.height,
          t = file.type, // ext only: // file.type.split('/')[1],
          n = file.name,
          s = ~~(file.size/1024) +'KB';
      $('#uploadPreview').append('<img src="' + this.src + '" class="thumb">');
    };

    image.onerror= function() {
      alert('Invalid file type: '+ file.type);
    };
  };

}
$("#image_file").change(function (e) {
  if(this.disabled) {
    return alert('File upload not supported!');
  }

  var F = this.files;
  if (F && F[0]) {
    for (var i = 0; i < F.length; i++) {
      readImage(F[i]);
    }
  }
});
</script>

Start Development server

For start development server, Go to the browser and hit below the url.

http://localhost/demo/ajax/multipleImage

Conclusion

In this codeigniter ajax multiple images upload tutorial – We have created a form for showing and uploading a multiple images into database and folder.

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

3 replies to Upload Multiple Images in Codeigniter Using Ajax

  1. Can you do this tutorial using laravel …

  2. It is working for me
    Thanks

  3. Thank you for this helped me today.

Leave a Reply

Your email address will not be published. Required fields are marked *