Tugas 5 PBKK (B)

UPLOAD FILE

Untuk tugas kali ini, saya akan membuat fitur upload file sebagai gambar service yang ditawarkan.

1. Tambahkan method _uploadImage() dan _deleteImage() ke Service_model.php

Method ini akan menghandle upload dan delete gambar.

private function _uploadImage()
  {
    $config['upload_path']          = './upload/service/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['file_name']            = $this->service_id;
    $config['overwrite']      = true;
    $config['max_size']             = 1024; // 1MB
    // $config['max_width']            = 1024;
    // $config['max_height']           = 768;

    $this->load->library('upload', $config);

    if ($this->upload->do_upload('image')) {
      return $this->upload->data("file_name");
    }

    return "default.jpg";
  }

  private function _deleteImage($id)
  {
    $service = $this->getById($id);
    if ($service->image != "default.jpg") {
      $filename = explode(".", $service->image)[0];
      return array_map('unlink', glob(FCPATH . "upload/service/$filename.*"));
    }
  }

2. Tambahkan pengecekan saat update

Hal ini penting jika service yang diupdate gambarnya tidak diubah atau malah dihapus. Masukkan snippet berikut di "Service_model.php"

public function update()
  {
    $post = $this->input->post();
    $this->service_id = $post["id"];
    $this->name = $post["name"];
    $this->price = $post["price"];


    if (!empty($_FILES["image"]["name"])) {
      $this->image = $this->_uploadImage();
    } else {
      $this->image = $post["old_image"];
    }

    $this->description = $post["description"];
    $this->db->update($this->_table, $this, array('service_id' => $post['id']));
  }

  public function delete($id)
  {
    $this->_deleteImage($id);
    return $this->db->delete($this->_table, array("service_id" => $id));
  }

3. Selesai

Sekarang service sudah bisa ditambahkan gambar, bukan gambar default lagi.
Tambah service tanpa gambar

List service tanpa gambar

Edit untuk menambah gambar

List service setelah ditambah gambar

Seperti biasa, source code bisa dilihat di sini

Comments