Senin, 11 April 2011

Codeigniter Upload Image

Berikut ini adalah cara menggunakan library upload pada Codeigniter, untuk kali ini saya akan menggunakan file image atau gambar dengan format 'jpg, gif atau png'

pertama kita mulai pada bagian view:
pada bagian view terdapat dua halaman yang pertama untuk halaman utama/halaman gagal upload, yang kedua adalah halaman sukses upload.

hal_utama.php

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo $error;?>
// jika file gagal d upload maka muncul error messgae

<?php echo form_open_multipart('upload/upload_file');?>
//form pembuka yg telah dilengkapi multipart form data

<input type="file" name="fupload" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

</body>
</html>

hal_sukses.php

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<h3>Your file was successfully uploaded!</h3>

<ul>
<?php foreach($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li> // jika file berhasil di upload akan muncul informasi tentang file trsebut
<?php endforeach; ?>
</ul>

<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>

</body>
</html>


selanjutnya pada bagian Controller

upload.php

<?php

class Upload extends CI_Controller {

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

function index()
{
$this->load->view('hal_utama', array('error' => ' ' ));
}

function upload_file()
{
$config['upload_path'] = './file/gambar/'; //direktori tempat gambar
$config['allowed_types'] = 'gif|jpg|png'; // jenis file yg boleh di upload
$config['max_size'] = '100'; // max ukuran file
$config['max_width'] = '1024';
$config['max_height'] = '768';

$this->load->library('upload', $config); // perintah konfigurasi pada library upload

if ( ! $this->upload->do_upload()) // perintah upload
{
$error = array('error' => $this->upload->display_errors());

$this->load->view('hal_utama', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());

$this->load->view('hal_ sukses', $data);
}
}
}
?>

kode di atas sudah cukup berfungsi, tpi saya pernah mengalami error atau gagal upload, dan solusi yang saya temukan sebagai berikut , saya hanya menambahakan 'fupload' = nama file, pada controller

........
$this->load->library('upload', $config); // perintah konfigurasi pada library upload

if ( ! $this->upload->do_upload(fupload)) // saya menambahkan pada bagian ini
{
$error = array('error' => $this->upload->display_errors());

$this->load->view('hal_utama', $error);
}
else
.........

Tidak ada komentar:

Posting Komentar