Buatlah sebuah table untuk menyimpan data gambar yang di upload, disini saya membuat sebuah table dengan nama tb_gambar. Untuk membuat table silahkan copy script berikut:
CREATE TABLE `tb_gambar` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `gambar` VARCHAR(250) NULL DEFAULT NULL, `created_at` VARCHAR(50) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB
Kemudian buatlah sebuah folder dengan nama gambar di root folder project, folder ini nantinya berfungsi untuk menyimpan data gambar yang telah diupload.
Gambar 1: Folder gambar di root project |
Jika table dan folder di root project sudah dibuat, maka kita akan mulai ngoding, let's to code dude!!!
<?phpdefined('BASEPATH') or exit('No direct script access allowed');class Upload_gambar extends CI_Controller{public function __construct(){parent::__construct();$this->load->model("Model_upload");date_default_timezone_set("Asia/Jakarta"); // set datetime berdasarkan lokasi}public function index(){$data["title"] = "Upload dan Resize Gambar";$data["data_gambar"] = $this->Model_upload->get_gambar(); // passing data ke view$this->load->view('upload_gambar', $data);}public function ajax_upload(){if (isset($_FILES["gambar"]["name"])) {//konfigurasi$config["upload_path"] = './gambar';$config["allowed_types"] = 'jpg|jpeg|png|gif|';//load library upload$this->load->library("upload", $config);// lakukan uploadif (!$this->upload->do_upload("gambar")) {echo $this->upload->display_errors(); // error jika gambar tidak sesuai rule} else {$data_gambar = $this->upload->data(); // simpan gambar// compress image start$config['image_library'] = 'gd2';$config['source_image'] = './gambar/' . $data_gambar["file_name"];$config['create_thumb'] = false;$config['maintain_ratio'] = false;$config['quality'] = '60%';$config['width'] = 150;$config['height'] = 150;$config['new_image'] = './gambar/' . $data_gambar["file_name"];$this->load->library('image_lib', $config);$this->image_lib->resize();// end compress setup// data yg akan disimpan$data_gambar2 = ['gambar' => $data_gambar["file_name"],'created_at' => date("d/M/Y - h:i:s A")];// call method simpan gambar$this->Model_upload->simpan_gambar($data_gambar2);//response ke ajaxecho $this->Model_upload->get_gambar();}}}}
<?phpclass Model_upload extends CI_Model{public function simpan_gambar($data){$this->db->insert('tb_gambar', $data);}public function get_gambar(){$output = "";$this->db->select("gambar");$this->db->from("tb_gambar");$this->db->order_by("id", "DESC");$query = $this->db->get()->result();foreach ($query as $row) {$output .= '<div class="col-md-3"><br/><img src="' . base_url('gambar/' . $row->gambar) . '" class="img-responsive img-thumbnail" /></div>';}return $output;}}
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title><?= $title; ?></title><!-- CDN Bootstrap --><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"><!-- CDN Jquery --><script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script></head><body><div class="container mt-3" style="width:600px"><h4><?= $title; ?></h4><br /><form method="POST" id="form_upload" enctype="multipart/form-data"><input type="file" name="gambar" id="gambar" class="form-control"><br /><button type="submit" class="btn btn-sm btn-primary">Upload gambar</button></form><div id="gambar_diupload"><br /><?= $data_gambar; ?></div></div></body></html><script>$(document).ready(() => {$("#form_upload").on("submit", function(event) {event.preventDefault();const base_url = "<?= base_url() ?>";if ($("#gambar").val() == "") {alert("Tidak ada gambar yang akan diupload");} else {$.ajax({url: base_url + "upload_gambar/ajax_upload",method: "POST",data: new FormData(this),contentType: false,cache: false,processData: false,success: (data) => {$("#gambar_diupload").html(data);}});}});});</script>
Demo program:
Gambar yang telah diupload akan di compress secara otomatis, kita bisa liat dari video demo diatas bahwa ukuran gambar sebelum diupload dan sesudah diupload telah berubah.
Semoga bermanfaat dude!!!
0 Komentar