Wednesday 19 June 2013

Code Igniter : Upload File

Langkah-langkah untuk upload file ke dalam server dengan menggunakan button sahaja seperti di bawah:-




View

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php        

echo form_open_multipart('upload/do_upload');               

echo form_upload('userfile','','id="userfile" style="position:absolute;visibility:hidden;" onchange="tmpFile.value=userfile.value;upload.click();"');       

?>

<button type="button" class="btn btn-primary" id="btnUpload" name="btnUpload" onClick="userfile.click();"><i class="icon-picture icon-white"></i> Upload Picture</button>               

<?php   

echo form_submit('upload', 'Upload Picture', 'class="btn-primary" id="upload" style="position:absolute;visibility:hidden;"');

echo form_hidden('tmpFile','','id="tmpFile"');

echo form_close();

?>            


Controller


 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
class Upload extends MY_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    function do_upload()
    {                               
        if ($this->input->post('tmpFile')!='') {           
           
            $config['upload_path'] = './assets/img/photo/';

            $config['allowed_types'] = 'jpg';

            $config['max_size']    = '3072';

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

            if ( ! $this->upload->do_upload())
            {
                $error = array('error' => $this->upload->display_errors());                             
            }
            else
            {               
                $image_data = $this->upload->data();                                                                        
                $data = array(
                    'id_user_pc' => $id,
                    'applicant_photo' => $image_data['file_name']                                       );           
                $this->Mymodel->insert_data('table_name', $data);                            
            }
        }
        else
        {           
            //put error message and redirect to controller otherwise its do nothing
        }
    }



Model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Mymodel extends CI_Model {
   
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function insert_data($table,$data)
    {
        if ($this->db->insert($table, $data)) {
            return $this->db->insert_id();
        }
        else return false;
    }

}


Nota : Pastikan folder yang menyimpan gambar hendaklah mempunyai permission 0777. 

----------------------------------------------------------
Disediakan Oleh : Haslina Shamsudin
Sumber :
1. Sistem AHPiS
2. Contoh Basic Upload

4 comments: