Tuesday 10 March 2015

CodeIgniter_ Image _and _File _Upload

(1)first create "uploads" folder into root directory of codeigniter.


(2)write code for  "file_view.php" file & save it to  views folder:

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php $this->load->helper('form'); ?>
<?php echo $error;?> <!-- Error Message will show up here -->
<?php echo form_open_multipart('index.php/upload_controller/do_upload');?>
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</body>
</html>


(3)write code for "upload_controller.php" file & save it to  controllers folder:



<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload_Controller extends CI_Controller {
public function __construct() {
parent::__construct();

$this->load->helper('url');
}
public function file_view(){

$this->load->helper('form');

$this->load->view('file_view', array('error' => ' ' ));
}
public function do_upload(){
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "500048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "10000",
'max_width' => "102400"
);
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success',$data);
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('file_view', $error);
}
}
}
?>


(4)write code for  file   "upload_success.php"  & save it views folder:

<html>
<head>
<title>Upload File Specification</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<!-- Uploaded file specification will show up here -->
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('index.php/upload_controller/file_view', 'Upload Another File!'); ?></p>
</body>
</html>


(5)To run it open browser   &    type following:


"http://localhost/ci/index.php/upload_controller/file_view"




No comments:

Post a Comment