ribbon iwa

Cara Download File Pada CodeIgniter

tutorialswb


Selamat siang bagaimana kabar kalian, hari ini kami akan share cara download file pada codeigniter. Jika kalian mengikuti artikel-artikel kami yang sebelumnya telah kami posting yang berjudul CodeIgniter - Upload File menggunakan Aax Jquery tentu postingan ini merupakan lanjutan dari artikel sebelumnya, tentu dengan penambahan fitur download saja. Let's star...

Konfigurasi Base URL

Buka folder application / config / config.php
 $config['base_url'] = 'http://localhost/downloadci/'; 

Database

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

Koneksi Database

Buka folder application / config / database.php
 $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 Models

Buka folder application / models kemudian 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);
 }

 public function download($id){
  $query = $this->db->get_where('files',array('id'=>$id));
  return $query->row_array();
 }
 
}
?> 

Buat Controllers

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

class File 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(){
  //load session library to use flashdata
      $this->load->library('session');
  //fetch all files i the database
      $data['files'] = $this->files_model->getAllFiles();
      $this->load->view('file_upload', $data);
  }

  public function insert(){
  //load session library to use flashdata
      $this->load->library('session');

   //Check if file is not empty
      if(!empty($_FILES['upload']['name'])){
        $config['upload_path'] = 'upload/';
            //restrict uploads to this mime types
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['file_name'] = $_FILES['upload']['name'];
        
            //Load upload library and initialize configuration
        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        
        if($this->upload->do_upload('upload')){
            $uploadData = $this->upload->data();
            $filename = $uploadData['file_name'];

    //set file data to insert to database
            $file['description'] = $this->input->post('description');
            $file['filename'] = $filename;

            $query = $this->files_model->insertfile($file);
            if($query){
               header('location:'.base_url().$this->index());
               $this->session->set_flashdata('success','File uploaded successfully');
           }
           else{
               header('location:'.base_url().$this->index());
               $this->session->set_flashdata('error','File uploaded but not inserted to database');
           }

       }else{
         header('location:'.base_url().$this->index());
         $this->session->set_flashdata('error','Cannot upload file.'); 
     }
 }else{
    header('location:'.base_url().$this->index());
    $this->session->set_flashdata('error','Cannot upload empty file.');
}

}

public function download($id){
    $this->load->helper('download');
    $fileinfo = $this->files_model->download($id);
    $file = 'upload/'.$fileinfo['filename'];
    force_download($file, NULL);
}

}
 

Defaul Controller

Buka folder application / config / routes.php
 $route['default_controller'] = 'file'; 

Buat Views

Buka folder application / views kemudian buat file dengan nama file_upload.php

 <!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>File Upload Form</title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
 <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
 <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.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="#">File Upload dan Download Form CodeIgniter</a></li>
    </ul>
   </div>
  </div>
 </nav>
 <div class="container">
  <div class="row">
   <div class="col-sm-4">
    <form method="POST" action="<?php echo base_url(); ?>file/insert" enctype="multipart/form-data">
     <div class="form-group">
      <label>Description:</label>
      <input type="text" name="description" class="form-control" required>
     </div>
     <div class="form-group">
      <label>File:</label>
      <input type="file" name="upload" required>
     </div>
     <button type="submit" class="btn btn-primary">Save</button>
    </form>
    <?php
    if($this->session->flashdata('success')){
     ?>
     <div class="alert alert-success text-center" style="margin-top:20px;">
      <?php echo $this->session->flashdata('success'); ?>
     </div>
     <?php
    }

    if($this->session->flashdata('error')){
     ?>
     <div class="alert alert-danger text-center" style="margin-top:20px;">
      <?php echo $this->session->flashdata('error'); ?>
     </div>
     <?php
    }
    ?>
   </div>
   <br/>
   <div class="col-sm-8">
    <table id="example" class="display" style="width:100%">
     <thead>
      <tr>
       <th>ID</th>
       <th>Filename</th>
       <th>Description</th>
       <th>Download</th>
      </tr>
     </thead>
     <tbody>
      <?php
      foreach($files as $file){
       ?>
       <tr>
        <td><?php echo $file->id; ?></td>
        <td><?php echo $file->filename; ?></td>
        <td><?php echo $file->description; ?></td>
        <td><a href="<?php echo base_url().'file/download/'.$file->id; ?>" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-download-alt"></a></td>
        </tr>
        <?php
       }
       ?>
      </tbody>
     </table>
    </div>
   </div>
  </div>

  <script type="text/javascript">
   $(document).ready(function() {
    $('table.display').DataTable();
   } );
  </script>
 </body>
 </html> 

Kalian bisa mendownload filenya langsung dan kalian bisa mencoba dan memodifikasi sesuai dengan yang kalian inginkan


Sekian share kali ini semoga apa yang kami share bermanfaat bagi anda, jangan lupa share keteman dan kerabat kalian, Salam blogger...


SUBSCRIBE TO OUR NEWSLETTER

close