Upload File Menggunakan Codeigniter dan Ajax

Salah satu yang rada ruwet saat mencoba bikin form upload menggunakan ajax adalah bagaimana mendapatkan value  dari input form untuk file yang akan diupload. Setelah beberapa kali mencoba trik akhirnya dapat cara yang lumayan mudah, yaitu pake FormData. Contohnya kita akan mengambil nilai dari form input file dengan ID gambar, bisa kita coba dengan skrip kayak gini.

var file_data = $('#gambar').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);//menggunakan variable (nama form input 'file')

Contoh lengkapnya bisa kita buat dengan mengedit file controller Welcome.php di folder controller dan juga file welcome_message.php difolder view.

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    ?><!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Welcome to CodeIgniter</title>

        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    </head>
    <body>

    <div id="container">
        <h1>Welcome to Upload Pake CodeIgniter and Jquery!</h1>

        <form action="#">
            <input name='gambar' type='file' id='gambar'>
            <button class='btn-sm btn-primary' id='tambahgambar'>Upload</button>
        </form>
    </div>
    <script>
        $(document).on('click','#tambahgambar',function(e){
            e.preventDefault();
            var file_data = $('#gambar').prop('files')[0];
            var form_data = new FormData();

            form_data.append('file', file_data);
            $.ajax({
                url: '<?php echo site_url("welcome/uploadgambar") ?>', // point to server-side PHP script
                dataType: 'json',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function(data,status){
                    //alert(php_script_response); // display response from the PHP script, if any
                    if (data.status!='error') {
                        $('#gambar').val('');
                        alert(data.msg);
                    }else{
                        alert(data.msg);
                    }
                }
            });
        })
    </script>

    </body>
    </html>

Trus file Welcome.php di folder controller juga kita edit menjadi.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->view('welcome_message');
    }
    public function uploadgambar(){
        $config['upload_path'] = './assets/images/upload';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']  = '1000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';

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

        if ( ! $this->upload->do_upload('file')){
            $status = "error";
            $msg = $this->upload->display_errors();
        }
        else{
            $dataupload = $this->upload->data();
            $status = "success";
            $msg = $dataupload['file_name']." berhasil diupload";
        }
        $this->output->set_content_type('application/json')->set_output(json_encode(array('status'=>$status,'msg'=>$msg)));
    }

}

/* End of file Welcome.php */

Sehingga saat kita akses tampilannya menjadi.

upload ci & jquerySelamat mencoba. 😀

2 thoughts on “Upload File Menggunakan Codeigniter dan Ajax

  1. Pingback: Upload File Menggunakan Codeigniter dan jQuery – tuliskode

  2. Pingback: Upload File Menggunakan Codeigniter dan Ajax – tuliskode

Tinggalkan Balasan

This site uses Akismet to reduce spam. Learn how your comment data is processed.