ribbon iwa

CodeIgniter - Upload File Menggunakan Jquery Ajax

Selamat malam sobat blogger kali ini kami akan share bagaimana membuat form file upload menggunakan Jquery Ajax pada codeigniter. Jika kalian belum mendownload file codeigniter, kalian bisa mendownload file resminya pada website resmi codeigniter. Let's start...

tutorialswb

Konfigurasi Base URL
Berikutnya mengkonfigurasi url basis untuk memberi tahu codeigniter bahwa ini adalah URL dari aplikasi. 
 $config['base_url'] = 'http://localhost/codeajax/'; 

Database
Buat database dengan nama codeigniter kemudian masukan struktur database dibawah ini.
 CREATE TABLE `files` (
  `id` int(11) NOT NULL,
  `filename` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 

Koneksi Database
Buka folder application / config / database.php kemudian sesuaikan dengan nama database kalian
 $db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'codeigniter',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => TRUE,
 '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
); 

Buat Model
Buka folder application / models kemudia buat file dengan nama Files_model.php
 <?php
 class Files_model extends CI_Model {
  function __construct(){
   parent::__construct();
   $this->load->database();
  }
 
  public function getAllFiles(){
   $query = $this->db->get('files');
   return $query->result(); 
  }
 
  public function insertfile($file){
   return $this->db->insert('files', $file);
  }
 
 }
?> 

Buat Controllers
Buka folder application / controllers kemudian buat file dengan nama Upload.php
 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload extends CI_Controller {

 function  __construct() {
        parent::__construct();
        //load our helper
        $this->load->helper('url');
        //load our model
        $this->load->model('files_model');
    }

 public function index(){
  $this->load->view('file_upload');
 }

 public function fetch(){
  $result = $this->files_model->getAllFiles();

  foreach($result as $row){
   ?>
   <tr>
    <td><?php echo $row->id; ?></td>
    <td><?php echo $row->filename; ?></td>
    <td><img src="<?php echo 'upload/'.$row->filename; ?>" height="30px" width="30px"></td>
   </tr>
   <?php
  }
 }

 public function insert(){
  $output = array('error' => false);
        if(!empty($_FILES['file']['name'])){
            $config['upload_path'] = 'upload/';
            $config['file_name'] = $_FILES['file']['name'];
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            
            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            
            if($this->upload->do_upload('file')){
                $uploadData = $this->upload->data();
                $filename = $uploadData['file_name'];

    $file['filename'] = $filename;
    
    $query = $this->files_model->insertfile($file);
    if($query){
     $output['message'] = 'File uploaded successfully';
    }
    else{
     $output['error'] = true;
     $output['message'] = 'File uploaded but not inserted to database';
    }

            }else{
             $output['error'] = true;
    $output['message'] = 'Cannot upload file';
            }
        }else{
         $output['error'] = true;
   $output['message'] = 'Cannot upload empty file';
        }

        echo json_encode($output);
  
 }

}
 

Defenisikan Default Controller
Buka application / config / routes.php
 $route['default_controller'] = 'upload'; 

Buat Views
Buka folder application / views kemudian buat file dengan nama file_upload.php
 <!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>CodeIgniter Ajax File Upload</title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
 <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
</head>
<body>
 <nav class="navbar navbar-default navbar-static-top">
  <div class="container-fluid">
   <div class="navbar-header">
    <a class="navbar-brand" href="https://www.tutorialswb.com/">TutorialsWB</a>
    <ul class="nav navbar-nav">
     <li class="active"><a href="#">CodeIgniter Ajax File Upload</a></li>
    </ul>
   </div>
  </div>
 </nav>
 <div class="container">
  <div class="row">
   <div class="col-sm-4">
    <h3>File Upload Form</h3>
    <form id="uploadForm">
     <div class="form-group">
      <label>File:</label>
      <input type="file" name="upload" id="file">
     </div>
     <button type="submit" class="btn btn-primary">Save</button>
    </form>
    <div id="responseDiv" class="alert text-center" style="margin-top:20px; display:none;">
     <button type="button" class="close" id="clearMsg"><span aria-hidden="true">&times;</span></button>
     <span id="message"></span>
    </div>  
   </div>
   <div class="col-sm-8">
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>ID</th>
       <th>Filename</th>
       <th>Preview</th>
      </tr>
     </thead>
     <tbody id="tbody">
     </tbody>
    </table>
   </div>
  </div>
 </div>
 <script type="text/javascript">
  $(document).ready(function(){
   fetchTable();

   $('#uploadForm').submit(function(e){
    e.preventDefault();
    var url = '<?php echo base_url(); ?>';

    var reader = new FileReader();
    reader.readAsDataURL(document.getElementById('file').files[0]);

    var formdata = new FormData();
    formdata.append('file', document.getElementById('file').files[0]);
    $.ajax({
     method: 'POST',
     contentType: false,
     cache: false,
     processData: false,
     data: formdata,
     dataType: 'json',
     url: url + 'index.php/upload/insert',
     success: function(response){
      console.log(response);
      if(response.error){
       $('#responseDiv').removeClass('alert-success').addClass('alert-danger').show();
       $('#message').html(response.message);
      }
      else{
       $('#responseDiv').removeClass('alert-danger').addClass('alert-success').show();
       $('#message').html(response.message);
       fetchTable();
       $('#uploadForm')[0].reset();
      }
     }
    });
   });

   $('#clearMsg').click(function(){
    $('#responseDiv').hide();
   });

  });
  function fetchTable(){
   var url = '<?php echo base_url(); ?>';
   $.ajax({
    method: 'POST',
    url: url + 'index.php/upload/fetch',
    success: function(response){
     $('#tbody').html(response);
    }
   });
  }
 </script>
</body>
</html> 

Sekian share kali ini kalian bisa mendownload filenya langsung dengan menekan button dibawah ini.


Kalian bisa meninggalkan komentar dibawah ini, kami akan membalas komentar anda.


SUBSCRIBE TO OUR NEWSLETTER

close