CodeIgniter Ajax File Upload using jQuery

Installing CodeIgniter

If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter which is 3.1.7 that I've used in this tutorial. After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP. Then, you can test whether you have successfully installed codeigniter by typing your app name in your browser. In my case, I named my app as codeigniter_fileupload_ajax so I'm using the below code.
  1. localhost/codeigniter_fileupload_ajax
codeigniter successful install

Creating our Database

First we are going to create our database. 1. Open your phpMyAdmin. 2. Create a new database named codeigniter. 3. Click the database that we created, click SQL tab then paste the below code or import the included .sql file in the downloadable of this source code located in db folder.
  1. CREATE TABLE `files` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `filename` varchar(150) NOT NULL,

Connecting our App into our Database

Next, we're going to connect our codeigniter application to the database that we created earlier. 1. In your codeigniter app folder, open database.php located in application/config folder. 2. Update database.php with your credential the same as what I did in the image below. database is where we define the database that we created earlier. database configuration codeigniter

Configuring Base URL

Next, we configure our base url to tell codeigniter that this is the URL of our site/application. We're gonna be using this a lot that's why we need to configure this. 1. In your codeigniter app folder, open config.php located in application/config folder. 2. Find and edit the ff line:
  1. $config['base_url'] = 'http://localhost/codeigniter_fileupload_ajax/';
where codeigniter_fileupload_ajax is the name of your app folder.

Creating our Model

Next, we create the model for our app. Take note that the first letter of your model name should be in CAPITAL letter and the name of the model should be the same as the file name to avoid confusion. Create a file named Files_model.php in application/models folder of our app and put the ff codes.
  1. <?php
  2.         class Files_model extends CI_Model {
  3.                 function __construct(){
  4.                         parent::__construct();
  5.                         $this->load->database();
  6.                 }
  7.  
  8.                 public function getAllFiles(){
  9.                         $query = $this->db->get('files');
  10.                         return $query->result();
  11.                 }
  12.  
  13.                 public function insertfile($file){
  14.                         return $this->db->insert('files', $file);
  15.                 }
  16.  
  17.         }
  18. ?>

Creating our Controller

Next step is to create our controller. Controllers follow the same naming convention as models. Create a file named Upload.php in application/controllers folder of our app and put the ff codes.
  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class Upload extends CI_Controller {
  5.  
  6.         function  __construct() {
  7.         parent::__construct();
  8.         //load our helper
  9.         $this->load->helper('url');
  10.         //load our model
  11.         $this->load->model('files_model');
  12.     }
  13.  
  14.         public function index(){
  15.                 $this->load->view('file_upload');
  16.         }
  17.  
  18.         public function fetch(){
  19.                 $result = $this->files_model->getAllFiles();
  20.  
  21.                 foreach($result as $row){
  22.                         ?>
  23.                         <tr>
  24.                                 <td><?php echo $row->id; ?></td>
  25.                                 <td><?php echo $row->filename; ?></td>
  26.                                 <td><img src="<?php echo 'upload/'.$row->filename; ?>" height="30px" width="30px"></td>
  27.                         </tr>
  28.                         <?php
  29.                 }
  30.         }
  31.  
  32.         public function insert(){
  33.                 $output = array('error' => false);
  34.         if(!empty($_FILES['file']['name'])){
  35.             $config['upload_path'] = 'upload/';
  36.             $config['file_name'] = $_FILES['file']['name'];
  37.             $config['allowed_types'] = 'gif|jpg|png|jpeg';
  38.            
  39.             $this->load->library('upload', $config);
  40.             $this->upload->initialize($config);
  41.            
  42.             if($this->upload->do_upload('file')){
  43.                 $uploadData = $this->upload->data();
  44.                 $filename = $uploadData['file_name'];
  45.  
  46.                                 $file['filename'] = $filename;
  47.                                
  48.                                 $query = $this->files_model->insertfile($file);
  49.                                 if($query){
  50.                                         $output['message'] = 'File uploaded successfully';
  51.                                 }
  52.                                 else{
  53.                                         $output['error'] = true;
  54.                                         $output['message'] = 'File uploaded but not inserted to database';
  55.                                 }
  56.  
  57.             }else{
  58.                 $output['error'] = true;
  59.                                 $output['message'] = 'Cannot upload file';
  60.             }
  61.         }else{
  62.                 $output['error'] = true;
  63.                         $output['message'] = 'Cannot upload empty file';
  64.         }
  65.  
  66.         echo json_encode($output);
  67.                
  68.         }
  69.  
  70. }

Defining our Default Controller

Next, we are going to set our default controller so that if no controller is defined, this default controller will be used. Open routes.php located in application/config folder and set the default route to our user controller.
  1. $route['default_controller'] = 'upload';

Creating our Views

Lastly, we create the views of our app. Create the ff files inside application/views folder. file_upload.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <meta charset="utf-8">
  5.         <title>CodeIgniter Ajax File Upload</title>
  6.         <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7.         <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
  8. </head>
  9. <body>
  10. <div class="container">
  11.         <h1 class="page-header text-center">CodeIgniter Ajax File Upload</h1>
  12.         <div class="row">
  13.                 <div class="col-sm-4">
  14.                         <h3>File Upload Form</h3>
  15.                         <form id="uploadForm">
  16.                                 <div class="form-group">
  17.                                         <label>File:</label>
  18.                                         <input type="file" name="upload" id="file">
  19.                                 </div>
  20.                                 <button type="submit" class="btn btn-primary">Save</button>
  21.                         </form>
  22.                         <div id="responseDiv" class="alert text-center" style="margin-top:20px; display:none;">
  23.                                 <button type="button" class="close" id="clearMsg"><span aria-hidden="true">&times;</span></button>
  24.                                 <span id="message"></span>
  25.                         </div>         
  26.                 </div>
  27.                 <div class="col-sm-8">
  28.                         <table class="table table-bordered table-striped">
  29.                                 <thead>
  30.                                         <tr>
  31.                                                 <th>ID</th>
  32.                                                 <th>Filename</th>
  33.                                                 <th>Preview</th>
  34.                                         </tr>
  35.                                 </thead>
  36.                                 <tbody id="tbody">
  37.                                 </tbody>
  38.                         </table>
  39.                 </div>
  40.         </div>
  41. </div>
  42. <script type="text/javascript">
  43.         $(document).ready(function(){
  44.                 fetchTable();
  45.  
  46.                 $('#uploadForm').submit(function(e){
  47.                         e.preventDefault();
  48.                         var url = '<?php echo base_url(); ?>';
  49.  
  50.                         var reader = new FileReader();
  51.                 reader.readAsDataURL(document.getElementById('file').files[0]);
  52.  
  53.                         var formdata = new FormData();
  54.                         formdata.append('file', document.getElementById('file').files[0]);
  55.                         $.ajax({
  56.                                 method: 'POST',
  57.                                 contentType: false,
  58.                             cache: false,
  59.                             processData: false,
  60.                             data: formdata,
  61.                             dataType: 'json',
  62.                                 url: url + 'index.php/upload/insert',
  63.                                 success: function(response){
  64.                                         console.log(response);
  65.                                         if(response.error){
  66.                                                 $('#responseDiv').removeClass('alert-success').addClass('alert-danger').show();
  67.                                                 $('#message').html(response.message);
  68.                                         }
  69.                                         else{
  70.                                                 $('#responseDiv').removeClass('alert-danger').addClass('alert-success').show();
  71.                                                 $('#message').html(response.message);
  72.                                                 fetchTable();
  73.                                                 $('#uploadForm')[0].reset();
  74.                                         }
  75.                                 }
  76.                         });
  77.                 });
  78.  
  79.                 $('#clearMsg').click(function(){
  80.                         $('#responseDiv').hide();
  81.                 });
  82.  
  83.         });
  84.         function fetchTable(){
  85.                 var url = '<?php echo base_url(); ?>';
  86.                 $.ajax({
  87.                         method: 'POST',
  88.                         url: url + 'index.php/upload/fetch',
  89.                         success: function(response){
  90.                                 $('#tbody').html(response);
  91.                         }
  92.                 });
  93.         }
  94. </script>
  95. </body>
  96. </html>
This is where we find our jQuery codes. NOTE: Be sure to create an upload folder in the root folder of your app to hold the uploaded files. That ends this tutorial. Happy coding :)

Add new comment