Senin, 15 Juni 2015

FILE UPLOADING CLASS DENGAN CODEIGNITER

Posted by Syaiful  |  at  04.33

Pada sebuah form input php, pasti kita tidak lepas dari input file atau input gambar untuk mendukung sebuah artikel kita. Maka dari itu saya akan share skrip upload files pada codeigniter.
Pada codeigniter librari upload sendiri sudah tersedia tanpa kita harus membuat librari baru lagi. Pada codeigniter kita tinggal memanggil $this->load->library('upload') untuk mempersingkat waktu mari kita mulai implementasinya
Langkah 1 : Buat database

1
2
3
4
5
6
7
CREATE TABLE `tb_uploadimage` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `nm_gbr` varchar(35) DEFAULT NULL,
  `tipe_gbr` varchar(10) DEFAULT NULL,
  `ket_gbr` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

Langkah 2 : Views
pertama buat view untuk tampilan awalnya dimana semua data yang ada didatabase ditampilkan beri nama vupload.php simpan di folder application/views

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<head>
    <title><?=$titel?></title> <!-- variabel diambil dari controller -->
     
    <link href="<?=base_url()?>assets/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap core CSS -->
    <link href="<?=base_url()?>assets/css/style.css" rel="stylesheet"> <!-- Custom styles for this template -->
<style>

    body{
        margin:20px 10%;
    }
</style>
</head>

<div class="container">
      <!-- Main component for a primary marketing message or call to action -->
<div class="panel panel-default">
  <div class="panel-heading"><b> Daftar File IMage</b></div>
  <div class="panel-body">
     
    <?=$this->session->flashdata('pesan')?>
    <p>
        <a href="<?=base_url()?>upload/add" class="btn btn-success">Tambah</a>
    </p>
  <table class="table table-bordered table-striped">
    <tr>
      <th>Keterangan File</th>
      <th>Tipe File</th>
      <th>Gambar File</th>
    </tr>
    <? if(empty($query)){ ?> <!-- jika data kosong kita tampilkan pesan -->
    <tr>
        <td colspan="3">Data tidak ada</td>
    </tr>
    <? }else{
    foreach($query as $rowdata){ ?> <!-- menampilkan data dari query dengan looping -->
    <tr>
      <td><?=$rowdata->ket_gbr?></td>
      <td><?=$rowdata->tipe_gbr?></td>
      <td><img src="assets/uploads/<?=$rowdata->nm_gbr?>"></td>
    </tr>
    <? }}?>
  </table>

</div>
</div>
</div>

Kemudian untuk view form nya simpan dengan nama fupload.php dan simpan juga di application/views

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<head>
    <title><?=$titel?></title> <!-- variabel diambil dari controller -->
     
    <link href="<?=base_url()?>assets/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap core CSS -->
    <link href="<?=base_url()?>assets/css/style.css" rel="stylesheet"> <!-- Custom styles for this template -->
<style>

    body{
        margin:20px 10%;
    }
</style>
</head>

<div class="container">
      <!-- Main component for a primary marketing message or call to action -->
<div class="panel panel-default">
  <div class="panel-heading"><b>Form Upload Image</b></div>
  <div class="panel-body">
  <?=$this->session->flashdata('pesan')?>
     <form action="<?=base_url()?>upload/insert" method="post" enctype="multipart/form-data">
       <table class="table table-striped">
         <tr>
          <td style="width:15%;">File Foto</td>
          <td>
            <div class="col-sm-6">
                <input type="file" name="filefoto" class="form-control">
            </div>
            </td>
         </tr>
         <tr>
          <td style="width:15%;">Keterangan Foto</td>
          <td>
            <div class="col-sm-10">
                <textarea name="textket" class="form-control"></textarea>
            </div>
            </td>
         </tr>
         <tr>
          <td colspan="2">
            <input type="submit" class="btn btn-success" value="Simpan">
            <button type="reset" class="btn btn-default">Batal</button>
          </td>
         </tr>
       </table>
     </form>
    </div>
   </div>    <!-- /panel -->
 </div> <!-- /container -->

Langkah 3 : Controllers
buat file controller beri nama upload.php dan simpan difolder application/controllers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends CI_Controller
{
    var $limit=10;
    var $offset=10;

    public function __construct() {
        parent::__construct();
        $this->load->model('mupload'); //load model mupload yang berada di folder model
        $this->load->helper(array('url')); //load helper url

    }

    public function index($page=NULL,$offset='',$key=NULL)
    {
        $data['titel']='Upload CodeIgniter'; //varibel title
         
        $data['query'] = $this->mupload->get_allimage(); //query dari model
         
        $this->load->view('vupload',$data); //tampilan awal ketika controller upload di akses
    }
    public function add() {
         
        $data['titel']='Form Upload CodeIgniter'; //varibel title
         
        //view yang tampil jika fungsi add diakses pada url
        $this->load->view('fupload',$data);
        
    }
    public function insert(){
        $this->load->library('upload');
        $nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
        $config['upload_path'] = './assets/uploads/'; //path folder
        $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
        $config['max_size'] = '2048'; //maksimum besar file 2M
        $config['max_width']  = '1288'; //lebar maksimum 1288 px
        $config['max_height']  = '768'; //tinggi maksimu 768 px
        $config['file_name'] = $nmfile; //nama yang terupload nantinya

        $this->upload->initialize($config);
         
        if($_FILES['filefoto']['name'])
        {
            if ($this->upload->do_upload('filefoto'))
            {
                $gbr = $this->upload->data();
                $data = array(
                  'nm_gbr' =>$gbr['file_name'],
                  'tipe_gbr' =>$gbr['file_type'],
                  'ket_gbr' =>$this->input->post('textket')
                   
                );

                $this->mupload->get_insert($data); //akses model untuk menyimpan ke database
                //pesan yang muncul jika berhasil diupload pada session flashdata
                $this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-success\" id=\"alert\">Upload gambar berhasil !!</div></div>");
                redirect('upload'); //jika berhasil maka akan ditampilkan view vupload
            }else{
                //pesan yang muncul jika terdapat error dimasukkan pada session flashdata
                $this->session->set_flashdata("pesan", "<div class=\"col-md-12\"><div class=\"alert alert-danger\" id=\"alert\">Gagal upload gambar !!</div></div>");
                redirect('upload/add'); //jika gagal maka akan ditampilkan form upload
            }
        }
    }
}

/* End of file upload.php */
/* Location: ./application/controllers/upload.php */

Pada skrip saya sudah buatkan keterangannya agar lebih mudah dipahami, kemudian saya juga include bootstrap js agar tampilan form lebih rapi. Jadi dengan kata lain bisa juga kita bilang upload image dengan tempalate bootstrap :D :D
Langkah 4 : Model
Kemudian selanjutnya kita buat skrip untuk modelnya, beri nama mupload.php simpan di folder application/models

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
class Mupload extends CI_Model {
    var $tabel = 'tb_uploadimage'; //buat variabel tabel

    function __construct() {
        parent::__construct();
    }
     
    //fungsi untuk menampilkan semua data dari tabel database
    function get_allimage() {
        $this->db->from($this->tabel);
        $query = $this->db->get();

        //cek apakah ada data
        if ($query->num_rows() > 0) {
            return $query->result();
        }
    }

    //fungsi insert ke database
    function get_insert($data){
       $this->db->insert($this->tabel, $data);
       return TRUE;
    }
}
?>

Langkah 5 : Setting
  1. Agar file berhasil disimpan buat folder assets/uploads karna path folder uploadnya saya buat seperti itu agan bisa ubah sesuai dengan selera agan
  2. Setting pada config/database.php setting agar konek ke database kita
  3. Setting pada config/routes.php agar langsung otomatis mengakses controller upload
1
$route['default_controller'] = "upload";

  1. Setting pada config/autoload.php agar terload otomatis
1
$autoload['libraries'] = array('database','session','form_validation');

  1. Kemudian pada config/config.php  buat seperti berikut pada base_url dan index_page
1
2
3
4
$config['base_url'] = "http://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME'])).'/';

$config['index_page'] = 'index.php';

  1. Kemudian buat sebuah file htaccess agar index.php pada url hilang buat seperti berikut dan simpan pada root folder proyek kit
1
2
3
4
5
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L]

Output













 sumber: http://fabernainggolan.net/upload-image-rename-codeigniter-dan-menyimpan-ke-database

About the Author

Write admin description here..

0 komentar:

Stats

Diberdayakan oleh Blogger.
back to top