Langsung saja saya berikan langkah-langkah dan penjelasan semampu saya.
Sebenarnya, pembuatan controller dan view untuk "halaman upload" ini tidaklah berbeda jauh dengan panduan di user guide CodeIgniter. Penambahan yang diberikan adalah pada proses uploadnya. Kita tambahkan fungsi javascript yang akan dieksekusi ketika button upload ditekan.
Kita buat form upload (upload_form.php) terlebih dahulu. (Mohon maaf banyak yang diremove oleh CI, silakan lihat di file yang saya sertakan di akhir artikel ini)
Perbedaan yang tampak adalah adanya beberapa file .js dan satu fungsi javascript yang ditambahkan. Sekarang kita buat controller...
<html> <head> <title>Upload Form</title> [removed][removed] [removed][removed] [removed] function ajaxFileUpload() { $("#loading") .ajaxStart(function(){ $(this).show(); }) .ajaxComplete(function(){ $(this).hide(); }); $.ajaxFileUpload ( { url:'<?php echo site_url()?>/upload/do_upload', secureuri:false, fileElementId:'fileToUpload', dataType: 'json', success: function (data, status) { if(typeof(data.error) != 'undefined') { if(data.error != '') { $("#info").html(data.error); }else { $("#info").html(data.msg); } } }, error: function (data, status, e) { $("#info").html(e); } } ) return false; } [removed] </head> <body> <form name="form" acti> <input id="fileToUpload" type="file" name="fileToUpload" size="20" /> <br /><br /> <button class="button" id="buttonUpload" >Upload</button> </form> <img id="loading" src="<?php echo base_url()?>asset/images/loading.gif" style="display:none;"> <div id="info"></div> </body> </html>
Jangan lupa untuk membuat folder "upload" dalam direktori yang sama dengan index.php. Terlihat mudah bukan?Silakan dicoba. Anda juga dapat mendownload paket file lengkapnya disini (pass:putraweb.net) .
class Upload extends Controller { function Upload() { parent::Controller(); } function index() { $this->load->view('upload_form'); } function do_upload() { $error = ""; $msg = ""; $config['upload_path'] = './upload/'; $config['allowed_types'] = 'doc|xls|ppt|pdf|rar|zip'; $config['max_size'] = '1000'; $this->load->library('upload', $config); $this->upload->display_errors('',''); if ( ! $this->upload->do_upload("fileToUpload")) { $error = $this->upload->display_errors(); } else { $msg = "File berhasil diupload"; } echo "{"; echo "error: '" . $error . "',\n"; echo "msg: '" . $msg . "'\n"; echo "}"; } }