การอัพโหลดไฟล์ด้วย file uploading class ใน codeigniter

เขียนเมื่อ 8 ปีก่อน โดย Ninenik Narkdee
codeigniter 3 codeigniter file uploading

คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ codeigniter 3 codeigniter file uploading

ดูแล้ว 18,484 ครั้ง


สำหรับเนื้อหาในการอัพโหลดไฟล์ นี้เราจะไม่ได้รวมในส่วนของ การใช้งาน
model ตามเนื้อหาตอนที่แล้ว แต่เราจะยังใช้รูปแบบเนื้อหาตอนที่แล้ว มาป็นส่วนในการ
ศึกษาเกี่ยวกับการใช้งาน file uploading class
 
ใช้งาน Form Validation สำหรับบันทึกและแก้ไขข้อมูลใน model ตอนที่ 3 
 
โดย class file uploading นี้ จะทำให้เราจัดการเกี่ยวกับการอัพโหลดต่างๆ ได้สะดวก
และง่ายขึ้น เช่น กำหนดชนิดไฟล์ที่อนุญาต ขนาดไฟล์ หรือถ้าเป็นรูปภาพก็ สามารถ
กำหนดขนาดความกว้าง ความสูงได้ 
 
จากเนื้อหาตอนที่แล้ว ที่เราได้ข้ามในส่วนของการอัพโหลดรูปภาพ พร้อมกับการเพิ่มข้อมูล
โดยจะจัดการใส่ส่วนของฟังก์ชั่น create() ขอยกในส่วนของโค้ดฟังก์ชั่นมาบาง
ส่วนประกอบการศึกษา 
ไฟล์ Service_model.php ในโฟลเดอร์ apps > models > admin
 
<?php
class Service_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    }
    
    public function getlist(){
        $query = $this->db->get('tbl_service');
        return $query->result_array();
    }    
    
    public function create(){
        $newdata = array(
            'service_id' => NULL,
            'service_title' => $this->input->post('service_title'),
            'service_detail' => $this->input->post('service_detail'),
            'service_img' => '',
            'service_update' => date("Y-m-d H:i:s")
        );
        return $this->db->insert('tbl_service', $newdata);
    }
    
..................  
............  
...... 
 
 

การอัพโหลดไฟล์ด้วย file uploading class

 
ในการศึกษาเกี่ยวกับการอัพโหลดไฟล์ พร้อมบันทึกฐานข้อมูลจะขอแยกเป็น 2 กรณ๊คือ
1. ต้องการให้ทำการอัพโหลดไฟล์พร้อมๆ กับข้อมูลอื่นๆ เสมอ
กล่าวคือ กำหนดให้ต้องทำการอัพโหลดไฟล์ ทุกครั้งที่มีการเพิ่มข้อมูล
 
2. ต้องการให้สามารถเพิ่มข้อมูลอื่นๆ โดยที่จะอัพโหลดไฟล์หรือไม่ก็ได้
กล่าวคือ เมื่อมีการเพิ่มข้อมูล เราจะอัพโหลดรูปไปด้วยหรือไม่ก็ได้ ข้อมูลอื่นก็ยังถูกเพิ่มไปปกติ
 
 

การอัพโหลดไฟล์ไปพร้อมๆ กับข้อมูลเสมอ

 
ก่อนอื่นให้เราเรียกใช้งาน library ที่ชื่อ upload ในส่วนของฟังก์ชั่น __construct() โดยเพิ่มโค้ดดังนี้
 
$this->load->library('upload');
 
จะได้เป็น
 
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
        $this->load->library('upload');
    }
 
เสร็จแล้วให้เราสร้างโฟลเดอร์ ชื่อ upload ไว้ที่ตำแหน่ง root ของโปรเจ็ค 
หรือที่เดียวกับโฟลเดอร์ apps และ sys 
หากอัพไฟล์ขึ้น server อย่าลืมเปิด permission โฟลเดอร์นี้ให้สามารถเขียนได้
 
จากนั้นเรามาดูที่ฟังก์ชั่น create() โดยจะเพิ่มการกำหนดการตั้งค่าการอัพโหลด ดังนี้
 
        $config['upload_path'] = './upload/';  // โฟลเดอร์ ตำแหน่งเดียวกับ root ของโปรเจ็ค
        $config['allowed_types'] = 'gif|jpg|png'; // ปรเเภทไฟล์ 
        $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB
        $config['max_width'] = '1024';  // ความกว้างรูปไม่เกิน
        $config['max_height'] = '768'; // ความสูงรูปไม่เกิน
        $config['file_name'] = 'mypicture';  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม
 
การกำหนดค่าอื่นๆ เพิ่มเติม สามารถดูได้ในคู่มือ
Preference Default Value Options Description
upload_path None None The path to the directory where the upload should be placed. The directory must be writable and the path can be absolute or relative.
allowed_types None None The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Can be either an array or a pipe-separated string.
file_name None Desired file name If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. If no extension is provided in the original file_name will be used.
file_ext_tolower FALSE TRUE/FALSE (boolean) If set to TRUE, the file extension will be forced to lower case
overwrite FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists.
max_size 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.
max_width 0 None The maximum width (in pixels) that the image can be. Set to zero for no limit.
max_height 0 None The maximum height (in pixels) that the image can be. Set to zero for no limit.
min_width 0 None The minimum width (in pixels) that the image can be. Set to zero for no limit.
min_height 0 None The minimum height (in pixels) that the image can be. Set to zero for no limit.
max_filename 0 None The maximum length that a file name can be. Set to zero for no limit.
max_filename_increment 100 None When overwrite is set to FALSE, use this to set the maximum filename increment for CodeIgniter to append to the filename.
encrypt_name FALSE TRUE/FALSE (boolean) If set to TRUE the file name will be converted to a random encrypted string. This can be useful if you would like the file saved with a name that can not be discerned by the person uploading it.
remove_spaces TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to underscores. This is recommended.
detect_mime TRUE TRUE/FALSE (boolean) If set to TRUE, a server side detection of the file type will be performed to avoid code injection attacks. DO NOT disable this option unless you have no other option as that would cause a security risk.
mod_mime_fix TRUE TRUE/FALSE (boolean) If set to TRUE, multiple filename extensions will be suffixed with an underscore in order to avoid triggering Apache mod_mime. DO NOT turn off this option if your upload directory is public, as this is a security risk.
 
ต่อไปก็เรียกใช้การตั้งค่าที่กำหนด ด้วยคำสั่ง
 
        $this->upload->initialize($config);      
 
ตามด้วยทำการอัพโหลดด้วยคำสั่ง
 
       $this->upload->do_upload('service_image');
 
โดยค่า service_image ก็คือชื่อของ input file ที่เรากำหนด
 
หากไม่มีปัญหาหรือข้อผิดพลาดใดๆ ในการอัพโหลดไฟล์ เราสามรถเรียกดูข้อมูล
ต่างๆ ของไฟล์ที่อัพโหลดได้จากคำสั่ง
 
$file_upload=$this->upload->data('file_name');
 
โดย file_name คือค่าเราต้องการรู้ ซึ่งหมายถึงชื่อไฟล์ที่อัพโหลดและเปลี่ยนชื่อแล้ว 
ถ้ากำหนดให้เปลี่ยนชื่อด้วย
ค่าอื่นๆ เช่น file_ext file_size file_path เป็นต้นดูได้ในคู่มือถ้าต้องการใช้งาน
 
Item Description
file_name Name of the file that was uploaded, including the filename extension
file_type File MIME type identifier
file_path Absolute server path to the file
full_path Absolute server path, including the file name
raw_name File name, without the extension
orig_name Original file name. This is only useful if you use the encrypted name option.
client_name File name as supplied by the client user agent, prior to any file name preparation or incrementing
file_ext Filename extension, period included
file_size File size in kilobytes
is_image Whether the file is an image or not. 1 = image. 0 = not.
image_width Image width
image_height Image height
image_type Image type (usually the file name extension without the period)
image_size_str A string containing the width and height (useful to put into an image tag)
จากโค้ดด้านบน คือถ้าอัพโหลดไฟล์ได้แล้ว ให้เอาชื่อไฟล์มาไว้ในตัวแปร $file_upload
เพื่อใช้ในการบันทึกลงฐานข้อมูล


 
ต่อมาเป็นการตรวจสอบการอัพโหลดไฟล์ และการบันทึกข้อมูล ดูโค้ดด้านล่างพร้อมคำ
อธิบายในโค้ด
 
        if($this->upload->display_errors()){ // ถ้าเกิดข้อมผิดพลาดในการอัพโหลดไฟล์
            return;
        }else{  // หากไม่มีข้อผิดพลาดใดๆ เกิดข้อ ก็บันทึกข้อมูลส่วนอื่นตามปกติ
            $newdata = array(
                'service_id' => NULL,
                'service_title' => $this->input->post('service_title'),
                'service_detail' => $this->input->post('service_detail'),
                'service_img' => $file_upload,
                'service_update' => date("Y-m-d H:i:s")
            );
            return $this->db->insert('tbl_service', $newdata);            
        }
 
เราจะได้ในส่วนของฟังก์ชั่น create() ดังนี้
 
    public function create(){
        $config['upload_path'] = './upload/';  // โฟลเดอร์ ตำแหน่งเดียวกับ root ของโปรเจ็ค
        $config['allowed_types'] = 'gif|jpg|png'; // ปรเเภทไฟล์ 
        $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB
        $config['max_width'] = '1024';  // ความกว้างรูปไม่เกิน
        $config['max_height'] = '768'; // ความสูงรูปไม่เกิน
        $config['file_name'] = 'mypicture';  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม

        $this->upload->initialize($config);    // เรียกใช้การตั้งค่า  
        $this->upload->do_upload('service_image'); // ทำการอัพโหลดไฟล์จาก input file ชื่อ service_image
        
        $file_upload=$this->upload->data('file_name');  // ถ้าอัพโหลดได้ เราสามารถเรียกดูข้อมูลไฟล์ที่อัพได้
        if($this->upload->display_errors()){ // ถ้าเกิดข้อมผิดพลาดในการอัพโหลดไฟล์
            return;
        }else{  // หากไม่มีข้อผิดพลาดใดๆ เกิดข้อ ก็บันทึกข้อมูลส่วนอื่นตามปกติ
            $newdata = array(
                'service_id' => NULL,
                'service_title' => $this->input->post('service_title'),
                'service_detail' => $this->input->post('service_detail'),
                'service_img' => $file_upload,
                'service_update' => date("Y-m-d H:i:s")

            );
            return $this->db->insert('tbl_service', $newdata);            
        }
    }
 
 
ทีนี้เรามาดูในส่วนของไฟล์ views ชื่อ admin_service.php ในโฟลเดอร์ apps > views > admin
ให้ดูในสวนของ $action เท่ากับ create ขอยกในส่วนของการตรวจสอบฟอร์มจาก form validation
มาให้ดู
 
<?php  
$this->form_validation->set_rules('service_title', 'Title', 'required');  
$this->form_validation->set_rules('service_detail', 'Detail', 'required');  
  
if($this->form_validation->run() === FALSE){ // ถ้าตรวจสอบไม่ผ่าน ให้ทำงาน  
//    echo "Error";  
}else{  // กรณีตรวจสอบผ่าน  
    $query = $this->service_model->create();  
    if($query){ // เมื่อเพิ่มข้อมูลเรียบร้อยแล้ว  
        redirect('admin/service'); // ไปหน้า service    
    }  
}  
                              
if(validation_errors()){ // ถ้ามีเงื่อนไขหนึ่งใดไม่ผ่าน ให้แสดง ข้อความ error ตำแหน่งนี้  
    echo   validation_errors();  
    echo "<br>";  
}
?>
 
จากโค้ดเราจะเห็นว่าเรามีการตรวจสอบแค่ title และ detail แต่กรณีนี้ เราต้องการตรวจสอบไฟล์
ที่อัพโหลดด้วย ตามเงื่อนไขว่า ไฟล์จะต้องถูกอัพโหลดไปพร้อมกับข้อมมูลเสมอ เราจึงจะเพิ่มใน
ส่วนของการตรวจสอบการอัพโหลดไฟล์เข้าไป
แต่เนืองด้วย codeigniter ไม่มี rule โดยตรงในการใช้งาน เราจึงประยุกต์เพิ่มเติมเป็นดังนี้
 
$this->form_validation->set_rules('service_title', 'Title', 'required');  
$this->form_validation->set_rules('service_detail', 'Detail', 'required');  
if(isset($_FILES['service_image']['name']) && $_FILES['service_image']['name']==""){
    $this->form_validation->set_rules('service_image', 'Image', 'required');
}
 
จากโค้ดในส่วนของรูปภาพ ได้ความหมายว่า ถ้ามีข้อมูลจาก input file แต่ไม่มีชื่อไฟล์ หรือชื่อไฟล์
เท่ากับว่าง ซึ่งก็คือ ไม่ได้เลือกไฟล์ ให้เราไปทำการกำหนด rule ให้กับ input file ชื่อ service_image
โดยเป็นเพียงรูปแบบการเช็คว่ามีค่ามาหรือไม่
 
และส่วนต่อมาที่เราจะเพิ่มคือ การแจ้งเตือน error เมือเงื่อนไขการอัพโหลดไฟล์ไม่ถูกต้อง
หรือก็คือกรณีไฟล์ใหญ่เกินไป ชนิด ประเภทไฟล์ไม่ถูกต้อง แบบนี้เป็นต้น ก็จะได้เป็น
 
if($this->upload->display_errors()){
    echo $this->upload->display_errors('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    echo "<br>";    
}
 
ดังนั้นเราจะได้ในส่วนของการตรวจสอบไฟล์ในกร๊แรกในส่วนของไฟล์ admin_service.php ตังนี้
 
<?php
$this->form_validation->set_rules('service_title', 'Title', 'required');
$this->form_validation->set_rules('service_detail', 'Detail', 'required');
if(isset($_FILES['service_image']['name']) && $_FILES['service_image']['name']==""){
    $this->form_validation->set_rules('service_image', 'Image', 'required');
}

if($this->form_validation->run() === FALSE){ // ถ้าตรวจสอบไม่ผ่าน ให้ทำงาน
//    echo "Error";
}else{  // กรณีตรวจสอบผ่าน
    $query = $this->service_model->create();
    if($query){ // เมื่อเพิ่มข้อมูลเรียบร้อยแล้ว
        redirect('admin/service'); // ไปหน้า service  
    }
}
                            
if(validation_errors()){ // ถ้ามีเงื่อนไขหนึ่งใดไม่ผ่าน ให้แสดง ข้อความ error ตำแหน่งนี้
    echo   validation_errors();
    echo "<br>";
}                           
if($this->upload->display_errors()){
    echo $this->upload->display_errors('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    echo "<br>";    
}
?>
 
 

การอัพโหลดไฟล์พร้อมกับข้อมูลอื่นด้วยหรือไม่ก็ได้ (ในตอนสรุปเราจะใช้รูปแบบนี้ในโปรเจ็คเรา)

 
ในแบบที่สองนี้ เราจะแก้ในส่วนของไฟล์ Service_model.php นิดหน่อย เป็นดังนี้
 
    public function create(){
        $config['upload_path'] = './upload/';  // โฟลเดอร์ ตำแหน่งเดียวกับ root ของโปรเจ็ค
        $config['allowed_types'] = 'gif|jpg|png'; // ปรเเภทไฟล์ 
        $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB
        $config['max_width'] = '1024';  // ความกว้างรูปไม่เกิน
        $config['max_height'] = '768'; // ความสูงรูปไม่เกิน
        $config['file_name'] = 'mypicture';  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม

        $this->upload->initialize($config);    // เรียกใช้การตั้งค่า  
        $this->upload->do_upload('service_image'); // ทำการอัพโหลดไฟล์จาก input file ชื่อ service_image
        
        $file_upload="";  // กำหนดชื่อไฟล์เป็นค่าว่าง 
        if(!$this->upload->display_errors()){ // ถ้าไม่มี error อัพไฟล์ได้ ให้เอาใช้ไฟล์ใส่ตัวแปร ไว้บันทึกลงฐานข้อมูล
            $file_upload=$this->upload->data('file_name');
        }
        $newdata = array(
            'service_id' => NULL,
            'service_title' => $this->input->post('service_title'),
            'service_detail' => $this->input->post('service_detail'),
            'service_img' => $file_upload,
            'service_update' => date("Y-m-d H:i:s")
        );
        return $this->db->insert('tbl_service', $newdata);                
    }
 
และในส่วนของไฟล์ admin_service.php ในกรณีอัพโหลดไฟล์ไปพร้อมกับบันทึกข้อมูลอื่นๆ ไปพร้อมกัน
หรือไม่่ก็ได้ ให้เราตัดในส่วนของการตรวจสอบไฟล์ออก จะได้เป็น
 
<?php
$this->form_validation->set_rules('service_title', 'Title', 'required');
$this->form_validation->set_rules('service_detail', 'Detail', 'required');

if($this->form_validation->run() === FALSE){ // ถ้าตรวจสอบไม่ผ่าน ให้ทำงาน
//    echo "Error";
}else{  // กรณีตรวจสอบผ่าน
    $query = $this->service_model->create();
    if($query){ // เมื่อเพิ่มข้อมูลเรียบร้อยแล้ว
        redirect('admin/service'); // ไปหน้า service  
    }
}
                            
if(validation_errors()){ // ถ้ามีเงื่อนไขหนึ่งใดไม่ผ่าน ให้แสดง ข้อความ error ตำแหน่งนี้
    echo   validation_errors();
    echo "<br>";
}                           
if($this->upload->display_errors()){
    echo $this->upload->display_errors('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    echo "<br>";    
}
?>

 

การอัพโหลดไฟล์กรณีทำการแก้ไขข้อมูล
 

สำหรับกรณีแก้ไขข้อมูลในฟังก์ชั่น edit() ที่มีการใช้งานการอัพโหลดไฟล์ จะขออธิบายแบบรวบรัด
ซึ่งรูปแบบก็จะไม่ต่างกับที่ใช้ในฟังก์ชั่น create()  แต่เราจะมีเพิ่มการส่งชื่อไฟล์เดิมเป็นแบบ hidden field 
เข้าไปด้วย โดยจะใช้ชื่อว่า h_service_image  จะได้ฟังก์ชั่นในการแก้ไขดังนี้
 
    public function edit($id){
        $config['upload_path'] = './upload/';  // โฟลเดอร์ ตำแหน่งเดียวกับ root ของโปรเจ็ค
        $config['allowed_types'] = 'gif|jpg|png'; // ปรเเภทไฟล์ 
        $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB
        $config['max_width'] = '1024';  // ความกว้างรูปไม่เกิน
        $config['max_height'] = '768'; // ความสูงรูปไม่เกิน
        $config['file_name'] = 'mypicture';  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม

        $this->upload->initialize($config);    // เรียกใช้การตั้งค่า  
        $this->upload->do_upload('service_image'); // ทำการอัพโหลดไฟล์จาก input file ชื่อ service_image
        
        $file_upload=$this->input->post('h_service_image');  // เก็บชื่อไฟล์เพิมถ้ามี
        if(!$this->upload->display_errors()){ // ถ้าไม่มี error อัพไฟล์ได้ ให้เอาใช้ไฟล์ใส่ตัวแปร ไว้บันทึกลงฐานข้อมูล
            $file_upload=$this->upload->data('file_name');  // เก็บชื่อไฟล์ใหม่           
        }else{
            // ถ้า error ในกรณีเลือกไฟล์แล้วไม่ผ่าน
            if($this->upload->data('file_type')){ // เช่น ประเภทไม่ถูกต้อง
                return; // ต้อง return เพื่อให้แสดง error
            }
        }        
        $newdata = array(
            'service_title' => $this->input->post('service_title'),
            'service_detail' => $this->input->post('service_detail'),
            'service_img' => $file_upload,
            'service_update' => date("Y-m-d H:i:s")
        );
        return $this->db->update('tbl_service', $newdata,array('service_id'=>$id));
    }  
 
 
ต่อไปในส่วนของฟอร์มแก้ไขในหน้า views ไฟล์ admin_service.php เนื่องจากว่า
เราต้องมีการส่งชื่อไฟล์เดิมถ้ามีไปใช้ในการอัพเดทข้อมูล กรณีไม่ได้ทำการเลือกอัพโหลดไฟล์ใหม่
จึงต้องส่ง hidden field เพิ่มเข้าไป ดังนี้
 
<input type="hidden" name="h_service_image" value="<?=$row['service_img']?>">
 
และส่วนของการแสดง error กรณีไฟล์ที่อัพโหลดไม่ถูกต้อง ก็แทรกไปคล้ายๆ กับในส่วน $action เท่ากับ create
ก็จะได้เป็น
 
<?php if($action=="edit"){?>
<a href="<?=base_url('admin/service')?>" class="btn btn-warning btn-sm">< Back</a>
<br><br>
<?php
$this->form_validation->set_rules('service_title', 'Title', 'required');
$this->form_validation->set_rules('service_detail', 'Detail', 'required');

if($this->form_validation->run() === FALSE){ // ถ้าตรวจสอบไม่ผ่าน ให้ทำงาน
//    echo "Error";
}else{  // กรณีตรวจสอบผ่าน
    $query = $this->service_model->edit($id);
    if($query){ // เมื่อแก้ไขข้อมูลเรียบร้อยแล้ว
        redirect('admin/service'); // ไปหน้า service  
    }
}
                            
if(validation_errors()){ // ถ้ามีเงื่อนไขหนึ่งใดไม่ผ่าน ให้แสดง ข้อความ error ตำแหน่งนี้
    echo   validation_errors();
    echo "<br>";
}
if($this->upload->display_errors()){
    echo $this->upload->display_errors('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    echo "<br>";    
}
// เรียกใช้ฟังก์ชั่น view() ดึงข้อมูลมาแสดงก่อนแก้ไข    
$row = $this->service_model->view($id);             
?>
<form action="<?=base_url('admin/service/edit/'.$id)?>" method="post" enctype="multipart/form-data">
<table class="table table-bordered">
<thead>
    <tr class="active">
        <th colspan="2">Edit Service</th>
    </tr>
</thead>
<tbody>
    <tr >
        <th width="120">Title:</th>
        <td>
            <input type="text" name="service_title" value="<?=$row['service_title']?>" style="width:500px;">
        </td>
    </tr>
    <tr>
        <th width="120">Detail:</th>
        <td>
        <textarea name="service_detail" cols="85" rows="10"><?=$row['service_detail']?></textarea>
        </td>
    </tr>    
    <tr>
        <th width="120">Images:</th>
        <td>
        <input type="file" name="service_image" >
        <input type="hidden" name="h_service_image" value="<?=$row['service_img']?>">
        </td>
    </tr>    
    <tr>
        <th></th>
        <td>
            <input type="submit" class="btn btn-success btn-sm" name="btn_add" value="Edit Service">
        </td>
    </tr>
</tbody>
</table>   

        
</form>
<?php } ?>
 
 

เราจะได้ไฟล์ Service_model.php ในโฟลเดอร์ apps > models > admin ดังนี้

<?php
class Service_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
        $this->load->library('upload');
    }
    
    public function getlist(){
        $query = $this->db->get('tbl_service');
        return $query->result_array();
    }    
    
    public function create(){
        $config['upload_path'] = './upload/';  // โฟลเดอร์ ตำแหน่งเดียวกับ root ของโปรเจ็ค
        $config['allowed_types'] = 'gif|jpg|png'; // ปรเเภทไฟล์ 
        $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB
        $config['max_width'] = '1024';  // ความกว้างรูปไม่เกิน
        $config['max_height'] = '768'; // ความสูงรูปไม่เกิน
        $config['file_name'] = 'mypicture';  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม

        $this->upload->initialize($config);    // เรียกใช้การตั้งค่า  
        $this->upload->do_upload('service_image'); // ทำการอัพโหลดไฟล์จาก input file ชื่อ service_image
        
        $file_upload="";  // กำหนดชื่อไฟล์เป็นค่าว่าง 
        if(!$this->upload->display_errors()){ // ถ้าไม่มี error อัพไฟล์ได้ ให้เอาใช้ไฟล์ใส่ตัวแปร ไว้บันทึกลงฐานข้อมูล
            $file_upload=$this->upload->data('file_name');
        }
        $newdata = array(
            'service_id' => NULL,
            'service_title' => $this->input->post('service_title'),
            'service_detail' => $this->input->post('service_detail'),
            'service_img' => $file_upload,
            'service_update' => date("Y-m-d H:i:s")
        );
        return $this->db->insert('tbl_service', $newdata);                
    }
    
    public function view($id){  // มี $id เป็น parameter ไว้กำหนดเงื่อนไข
        $query = $this->db->get_where('tbl_service',array('service_id'=>$id));
        return $query->row_array(); // ส่งข้อมูลผลัพธ์กลับเป็น array แถวข้อมูล
    }    
    
    public function edit($id){
        $config['upload_path'] = './upload/';  // โฟลเดอร์ ตำแหน่งเดียวกับ root ของโปรเจ็ค
        $config['allowed_types'] = 'gif|jpg|png'; // ปรเเภทไฟล์ 
        $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB
        $config['max_width'] = '1024';  // ความกว้างรูปไม่เกิน
        $config['max_height'] = '768'; // ความสูงรูปไม่เกิน
        $config['file_name'] = 'mypicture';  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม

        $this->upload->initialize($config);    // เรียกใช้การตั้งค่า  
        $this->upload->do_upload('service_image'); // ทำการอัพโหลดไฟล์จาก input file ชื่อ service_image
        
        $file_upload=$this->input->post('h_service_image');  // เก็บชื่อไฟล์เพิมถ้ามี
        if(!$this->upload->display_errors()){ // ถ้าไม่มี error อัพไฟล์ได้ ให้เอาใช้ไฟล์ใส่ตัวแปร ไว้บันทึกลงฐานข้อมูล
            $file_upload=$this->upload->data('file_name');  // เก็บชื่อไฟล์ใหม่           
        }else{
            // ถ้า error ในกรณีเลือกไฟล์แล้วไม่ผ่าน
            if($this->upload->data('file_type')){ // เช่น ประเภทไม่ถูกต้อง
                return; // ต้อง return เพื่อให้แสดง error
            }
        }        
        $newdata = array(
            'service_title' => $this->input->post('service_title'),
            'service_detail' => $this->input->post('service_detail'),
            'service_img' => $file_upload,
            'service_update' => date("Y-m-d H:i:s")
        );
        return $this->db->update('tbl_service', $newdata,array('service_id'=>$id));
    }  
    
    public function delete($id){
        return $this->db->delete('tbl_service', array('service_id' =>$id)); 
        // คืนค่าผลการคิวรี่
    }        

}
 
 
 
 

และไฟล์ admin_service.php ในโฟลเดอร์ apps > views > admin ดังนี้

<div class="container">
    
Service  
<br><br>
<?php if($action==null){?>
<?php
$result = $this->service_model->getlist();
?>
<a href="<?=base_url('admin/service/create')?>" class="btn btn-primary btn-sm">Create</a>
<br><br>
<table class="table table-striped table-bordered table-condensed">
    <thead>
        <tr>
            <th width="50" class="text-center">#</th>
            <th>Title</th>
            <th width="150" class="text-center">Modify Date</th>
            <th width="150" class="text-center">Manage</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $i_num=0;
        if(count($result)>0){
            foreach($result as $row){
                $i_num++;
        ?>
        <tr>
            <td class="text-center"><?=$i_num?></td>
            <td><?=$row['service_title']?></td>
            <td class="text-center"><?=$row['service_update']?></td>
            <td class="text-center">
                <a href="<?=base_url('admin/service/edit/'.$row['service_id'])?>" class="btn btn-success btn-sm">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                </a>
                &nbsp;&nbsp;
                 <a href="<?=base_url('admin/service/delete/'.$row['service_id'])?>" class="btn btn-danger btn-sm">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                </a>
                
            </td>
        </tr>
        <?php } ?>
        <?php } ?>
    </tbody>
</table>
<?php } ?>

<?php if($action=="create"){?>
<a href="<?=base_url('admin/service')?>" class="btn btn-warning btn-sm">< Back</a>
<br><br>
<?php
$this->form_validation->set_rules('service_title', 'Title', 'required');
$this->form_validation->set_rules('service_detail', 'Detail', 'required');

if($this->form_validation->run() === FALSE){ // ถ้าตรวจสอบไม่ผ่าน ให้ทำงาน
//    echo "Error";
}else{  // กรณีตรวจสอบผ่าน
    $query = $this->service_model->create();
    if($query){ // เมื่อเพิ่มข้อมูลเรียบร้อยแล้ว
        redirect('admin/service'); // ไปหน้า service  
    }
}
                            
if(validation_errors()){ // ถ้ามีเงื่อนไขหนึ่งใดไม่ผ่าน ให้แสดง ข้อความ error ตำแหน่งนี้
    echo   validation_errors();
    echo "<br>";
}                           
if($this->upload->display_errors()){
    echo $this->upload->display_errors('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    echo "<br>";    
}
?>
<form action="<?=base_url('admin/service/create')?>" method="post" enctype="multipart/form-data">
<table class="table table-bordered">
<thead>
    <tr class="active">
        <th colspan="2">Add New Service</th>
    </tr>
</thead>
<tbody>
    <tr >
        <th width="120">Title:</th>
        <td>
            <input type="text" name="service_title" value="<?=set_value('service_title')?>" style="width:500px;">
        </td>
    </tr>
    <tr>
        <th width="120">Detail:</th>
        <td>
        <textarea name="service_detail" cols="85" rows="10"><?=set_value('service_detail')?></textarea>
        </td>
    </tr>    
    <tr>
        <th width="120">Images:</th>
        <td>
        <input type="file" name="service_image" >
        </td>
    </tr>    
    <tr>
        <th></th>
        <td>
            <input type="submit" class="btn btn-success btn-sm" name="btn_add" value="Add Service">
        </td>
    </tr>
</tbody>
</table>    
    

</form>
<?php } ?>

<?php if($action=="edit"){?>
<a href="<?=base_url('admin/service')?>" class="btn btn-warning btn-sm">< Back</a>
<br><br>
<?php
$this->form_validation->set_rules('service_title', 'Title', 'required');
$this->form_validation->set_rules('service_detail', 'Detail', 'required');

if($this->form_validation->run() === FALSE){ // ถ้าตรวจสอบไม่ผ่าน ให้ทำงาน
//    echo "Error";
}else{  // กรณีตรวจสอบผ่าน
    $query = $this->service_model->edit($id);
    if($query){ // เมื่อแก้ไขข้อมูลเรียบร้อยแล้ว
        redirect('admin/service'); // ไปหน้า service  
    }
}
                            
if(validation_errors()){ // ถ้ามีเงื่อนไขหนึ่งใดไม่ผ่าน ให้แสดง ข้อความ error ตำแหน่งนี้
    echo   validation_errors();
    echo "<br>";
}
if($this->upload->display_errors()){
    echo $this->upload->display_errors('<div class="bg-danger" style="padding:3px 10px;">', '</div>');
    echo "<br>";    
}
// เรียกใช้ฟังก์ชั่น view() ดึงข้อมูลมาแสดงก่อนแก้ไข    
$row = $this->service_model->view($id);             
?>
<form action="<?=base_url('admin/service/edit/'.$id)?>" method="post" enctype="multipart/form-data">
<table class="table table-bordered">
<thead>
    <tr class="active">
        <th colspan="2">Edit Service</th>
    </tr>
</thead>
<tbody>
    <tr >
        <th width="120">Title:</th>
        <td>
            <input type="text" name="service_title" value="<?=$row['service_title']?>" style="width:500px;">
        </td>
    </tr>
    <tr>
        <th width="120">Detail:</th>
        <td>
        <textarea name="service_detail" cols="85" rows="10"><?=$row['service_detail']?></textarea>
        </td>
    </tr>    
    <tr>
        <th width="120">Images:</th>
        <td>
        <input type="file" name="service_image" >
        <input type="hidden" name="h_service_image" value="<?=$row['service_img']?>">
        </td>
    </tr>    
    <tr>
        <th></th>
        <td>
            <input type="submit" class="btn btn-success btn-sm" name="btn_add" value="Edit Service">
        </td>
    </tr>
</tbody>
</table>   

        
</form>
<?php } ?>

<?php if($action=="delete"){?>
<?php
$query = $this->service_model->delete($id);                                  
?>
<a href="<?=base_url('admin/service')?>" class="btn btn-warning btn-sm">< Back</a>
<br><br>
<?php if($query){?>
<div class="bg-success text-center" style="padding:10px;">
    <p class="text-success">Delete data complete</p>
    <a href="<?=base_url('admin/service')?>" class="text-success">< Back > </a>
</div>
<?php } ?>
<?php } ?>

</div>
 
 
เป็นอันจบในส่วนของการใช้งาน file uploading class ซึ่งค่อนข้างสะดวกเป็นอย่างมาก
และเหตุผลที่ต้องนำโค้ดทั้งหมดมาแสดงในส่วนท้ายสุดของบทความ ก็เนื่องด้วย 
การแนะนำโค้ดข้างต้น มีการสลับไปมาระหว่างไฟล์ในส่วน ของ model และ views
หลายคนอาจจะสับสน ดังนั้นจึงนำโค้ดสุดท้ายแต่ละรายการมาให้ สำหรับคนที่ศึกษา และทำตาม
 
ในเนื้อหาตอนต่อไป เราจะมาดูเรื่องของการลบไฟล์ รอติดตาม


กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ



อ่านต่อที่บทความ













URL สำหรับอ้างอิง





คำแนะนำ และการใช้งาน

สมาชิก กรุณา ล็อกอินเข้าระบบ เพื่อตั้งคำถามใหม่ หรือ ตอบคำถาม สมาชิกใหม่ สมัครสมาชิกได้ที่ สมัครสมาชิก


  • ถาม-ตอบ กรุณา ล็อกอินเข้าระบบ
  • เปลี่ยน


    ( หรือ เข้าใช้งานผ่าน Social Login )







เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ