WEb Programming: CI File Uploading Class (Multiple Files Too)

Sebelum masuk ke framework, yuk kita lihat kalo native-nya itu prosesnya bagaimana:

Overview
In this tutorial create 2 files
1. multiple_upload.php
2. multiple_upload_ac.phpStep
1. Create file multiple_upload.php
2. Create file multiple_upload_ac.php
3. Create folder “upload” for store uploaded files.
.4. CHMOD your upload folder to “777” by using your ftp software(change permission).
Create file multiple_upload.php
View in browser

############### Code<table width=”500″ border=”0″ align=”center” cellpadding=”0″ cellspacing=”1″ bgcolor=”#CCCCCC”>
<tr>
<form action=”multiple_upload_ac.php” method=”post” enctype=”multipart/form-data” name=”form1″ id=”form1″>
<td>
<table width=”100%” border=”0″ cellpadding=”3″ cellspacing=”1″ bgcolor=”#FFFFFF”>
<tr>
<td><strong>multiple Files Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name=”ufile[]” type=”file” id=”ufile[]” size=”50″ /></td>
</tr>
<tr>
<td>Select file
<input name=”ufile[]” type=”file” id=”ufile[]” size=”50″ /></td>
</tr>
<tr>
<td>Select file
<input name=”ufile[]” type=”file” id=”ufile[]” size=”50″ /></td>
</tr>
<tr>
<td align=”center”><input type=”submit” name=”Submit” value=”Upload” /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
Create file multiple_upload_ac.php
############### Code<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES[‘ufile’][‘name’]; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path1= “upload/”.$HTTP_POST_FILES[‘ufile’][‘name’][0];
$path2= “upload/”.$HTTP_POST_FILES[‘ufile’][‘name’][1];
$path3= “upload/”.$HTTP_POST_FILES[‘ufile’][‘name’][2];

//copy file to where you want to store file
copy($HTTP_POST_FILES[‘ufile’][‘tmp_name’][0], $path1);
copy($HTTP_POST_FILES[‘ufile’][‘tmp_name’][1], $path2);
copy($HTTP_POST_FILES[‘ufile’][‘tmp_name’][2], $path3);

//$HTTP_POST_FILES[‘ufile’][‘name’] = file name
//$HTTP_POST_FILES[‘ufile’][‘size’] = file size
//$HTTP_POST_FILES[‘ufile’][‘type’] = type of file
echo “File Name :”.$HTTP_POST_FILES[‘ufile’][‘name’][0].”<BR/>”;
echo “File Size :”.$HTTP_POST_FILES[‘ufile’][‘size’][0].”<BR/>”;
echo “File Type :”.$HTTP_POST_FILES[‘ufile’][‘type’][0].”<BR/>”;
echo “<img src=\”$path1\” width=\”150\” height=\”150\”>”;
echo “<P>”;

echo “File Name :”.$HTTP_POST_FILES[‘ufile’][‘name’][1].”<BR/>”;
echo “File Size :”.$HTTP_POST_FILES[‘ufile’][‘size’][1].”<BR/>”;
echo “File Type :”.$HTTP_POST_FILES[‘ufile’][‘type’][1].”<BR/>”;
echo “<img src=\”$path2\” width=\”150\” height=\”150\”>”;
echo “<P>”;

echo “File Name :”.$HTTP_POST_FILES[‘ufile’][‘name’][2].”<BR/>”;
echo “File Size :”.$HTTP_POST_FILES[‘ufile’][‘size’][2].”<BR/>”;
echo “File Type :”.$HTTP_POST_FILES[‘ufile’][‘type’][2].”<BR/>”;
echo “<img src=\”$path3\” width=\”150\” height=\”150\”>”;

///////////////////////////////////////////////////////

// Use this code to display the error or success.

$filesize1=$HTTP_POST_FILES[‘ufile’][‘size’][0];
$filesize2=$HTTP_POST_FILES[‘ufile’][‘size’][1];
$filesize3=$HTTP_POST_FILES[‘ufile’][‘size’][2];

if($filesize1 && $filesize2 && $filesize3 != 0)
{
echo “We have recieved your files”;
}

else {
echo “ERROR…..”;
}

//////////////////////////////////////////////

// What files that have a problem? (if found)

if($filesize1==0) {
echo “There’re something error in your first file”;
echo “<BR />”;
}

if($filesize2==0) {
echo “There’re something error in your second file”;
echo “<BR />”;
}

if($filesize3==0) {
echo “There’re something error in your third file”;
echo “<BR />”;
}

?>

CHMOD upload folder to 777 (change permission)
This step, do it when you upload to real server.
This example, I use WS-FTP, right click at upload folder > FTP Commands > CHMOD(Unix)

source: phpeasystep.com

Kalo digabung sedikit dengan javascript untuk dynamic file input form-nya:

<script type=”text/javascript”>
function add(type){
//Create an input type dynamically.
var element = document.createElement(“input”);
var div = document.createElement(‘div’);

//simulate static variable
//if(typeof self.cnt != ‘number’)cnt = -1;
//cnt++;
//let’s use array!

//assign attributes to the element
element.setAttribute(“type”, type);
element.setAttribute(“name”, “pic[]”);

div.setAttribute(“style”, “height:5px”);

var foo = document.getElementById(“foobar”);

//Append the element in page (in span).
foo.appendChild(div);
foo.appendChild(element);

}
</script>

<input type=”button” value=”add Picture” onclick=”add(‘file’)” />
<div id=”foobar”>&nbsp;</div>

Nah intinya kalo di CI, untuk supaya uploading class itu berjalan sebagaimana mestinya, ada beberapa hal yang musti diperhatikan keberadaannya.

Controller:

$config[‘upload_path’] = ‘./uploaded/temp/’; /*$_SERVER[‘DOCUMENT_ROOT’] kalo diserver-nya*/
$config[‘allowed_types’] = ‘gif|jpg|png’;
$this->load->library(‘upload’, $config);

$this->upload->display_errors(‘<span style=”color:#cc0000″>’, ‘</span>’);

Terus,

Cek kalo ada upaya upload atau tidaknya:

if(!$this->upload->do_upload(‘thumbnail’)) {

Nah kalo ada:

$file    = $this->upload->data();
$thumbnail = $file[‘file_name’];

Dan tidak lupa dengan penambahan helper custom (thanks to radhite)

kalo image, di resize dulu:

resizeimg(‘uploaded’,’default’,$file[‘file_name’],”,510,387);

dengan definisinya:

function resizeimg($modul,$folder,$filename,$marker,$w,$h) {
$CI = &get_instance();
$CI->load->library(‘image_lib’);

$config = array(
‘image_library’ => ‘GD2′,
/*’source_image’    => $_SERVER[‘DOCUMENT_ROOT’].’./resources/images/’.$modul.’/temp/’.$filename,
‘new_image’ => $_SERVER[‘DOCUMENT_ROOT’].’./resources/images/’.$modul.’/’.$folder.’/’.$filename,*/
‘source_image’    => /*$_SERVER[‘DOCUMENT_ROOT’].*/’./’.$modul.’/temp/’.$filename,
‘new_image’ => /*$_SERVER[‘DOCUMENT_ROOT’].*/’./’.$modul.’/’.$folder.’/’.$filename,
‘thumb_marker’ => $marker,
‘quality’ => 80,
‘create_thumb’ => TRUE,
‘maintain_ratio’ => TRUE,
‘width’ => $w,
‘height’ => $h
);
//var_dump($config);exit;
$CI->image_lib->initialize($config);

if (!$CI->image_lib->resize())
{
echo $folder.’ => ‘.$CI->image_lib->display_errors();
}
else
{
echo $CI->image_lib->clear();
}
}

View:

enctype-nya,

<form method=”post” action=”<?php echo base_url()?>admin/artikel/edit/<?php echo $id;?>” name=”myform” id=”myform” enctype=”multipart/form-data”>

dan nama fieldnya harus sama dengan yang dipanggil di Controller,

<tr valign=”top”><td>Thumbnail</td><td>:</td><td><?php if(!empty($thumbnail)){?><img src=”<?php echo base_url().’uploaded/thumb/’.$thumbnail ?>” alt=”<?php echo $thumbnail ?>” /><br /><?php } ?><input type=”file” name=”thumbnail” value=”” /></td></tr>

Udah deh, harusnya semua akan berjalan sebagaimana mestinya.

** Tambahan:

Untuk Multiple Files upload

Controller,

class Upload extends Controller {function Upload()
{
parent::Controller();
$this->load->helper(array(‘form’,’url’,’file’));

}

function index()
{

$this->load->view(‘upload/upload_index’); //Upload Form

}

function picupload()
{
//Load Model
$this->load->model(‘Process_image’);

$config[‘upload_path’] = ‘./uploads/’;
$config[‘allowed_types’] = ‘gif|jpg|png’;
$config[‘max_size’]    = ‘2048’; //2 meg

$this->load->library(‘upload’);

foreach($_FILES as $key => $value)
{
if( ! empty($key[‘name’]))
{
$this->upload->initialize($config);

if ( ! $this->upload->do_upload($key))
{
$errors[] = $this->upload->display_errors();

}
else
{

$this->Process_image->process_pic();

}
}

}

$data[‘success’] = ‘Thank You, Files Upladed!’;

$this->load->view(‘upload/upload_pictures’, $data); //Picture Upload View

}

Model,

class Process_image extends Model {function Process_image()
{
parent::Model();

$this->load->library(‘image_lib’);
//Generate random Activation code

function generate_code($length = 10){

if ($length <= 0)
{
return false;
}

$code = “”;
$chars = “abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789”;
srand((double)microtime() * 1000000);
for ($i = 0; $i < $length; $i++)
{
$code = $code . substr($chars, rand() % strlen($chars), 1);
}
return $code;

}

}

function process_pic()
{
//Connect to database
$this->load->database();

//Get File Data Info
$uploads = array($this->upload->data());

$this->load->library(‘image_lib’);

//Move Files To User Folder
foreach($uploads as $key[] => $value)
{

//Gen Random code for new file name
$randomcode = generate_code(12);

$newimagename = $randomcode.$value[‘file_ext’];

//Creat Thumbnail
$config[‘image_library’] = ‘GD2’;
$config[‘source_image’] = $value[‘full_path’];
$config[‘create_thumb’] = TRUE;
$config[‘thumb_marker’] = ‘_tn’;
$config[‘master_dim’] = ‘width’;
$config[‘quality’] = 75;
$config[‘maintain_ratio’] = TRUE;
$config[‘width’] = 175;
$config[‘height’] = 175;
$config[‘new_image’] = ‘/pictures/’.$newimagename;

//$this->image_lib->clear();
$this->image_lib->initialize($config);
//$this->load->library(‘image_lib’, $config);
$this->image_lib->resize();

//Move Uploaded Files with NEW Random name
rename($value[‘full_path’],’/pictures/’.$newimagename);

//Make Some Variables for Database
$imagename = $newimagename;
$thumbnail = $randomcode.’_tn’.$value[‘file_ext’];
$filesize = $value[‘file_size’];
$width = $value[‘image_width’];
$height = $value[‘image_height’];
$timestamp = time();

//Add Pic Info To Database
$this->db->set(‘imagename’, $imagename);
$this->db->set(‘thumbnail’, $thumbnail);
$this->db->set(‘filesize’, $filesize);
$this->db->set(‘width’, $width);
$this->db->set(‘height’, $height);
$this->db->set(‘timestamp’, $timestamp);

//Insert Info Into Database
$this->db->insert(‘pictures’);

}

}

Semoga bermanfaat.

Lebih detailnya bisa didapatkan di: codeigniter.com

Special thanks to Radhite for the helper

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s