Step 1
Create database : db_test
CREATE TABLE IF NOT EXISTS `tb_image` ( `image_ID` int(11) NOT NULL AUTO_INCREMENT, `file_name` varchar(100) NOT NULL, PRIMARY KEY (`image_ID`) );
Step 2
Create controller file. /application/controller/image_upload.php
<?php
class Image_upload extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$config = array(
'upload_path' => FCPATH.'upload/',
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => 0,
'file_name' => url_title($this->input->post('filename')),
'encrypt_name' => true
);
$this->load->library('upload', $config);
if ($this->upload->do_upload('filename')) {
$this->db->insert('tb_image', array(
'file_name' => $this->upload->filename
));
if ($this->db->affected_rows() > 0) {
$this->session->set_flashdata('msg', 'Image success uploaded.');
redirect('image_upload');
}
}
$data['result'] = $this->db->get('tb_image');
$this->load->view('image_upload', $data);
}
}
Step 3
Open file autoload.php. /application/config/autoload.php
<?php
$autoload['libraries'] = array(
'database',
'session',
'form_validation'
);
$autoload['helper'] = array(
'html',
'url'
);
Step 4
Open file database.php. /application/config/database.php
<?php
$db['default'] = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_test'
);
Step 5
Create view file. /application/views/image_upload.php
<html>
<head>
<title>Codeigniter Image Upload</title>
</head>
<body>
<?php
echo form_open_multipart();
echo form_upload('filename');
echo form_submit('upload', 'Upload');
echo form_close();
?>
<table width="100%">
<tr>
<th> </th>
<th>FILENAME</th>
<th>PATH</th>
</tr>
<?php
if ($result->num_rows() > 0) {
$i = 1;
foreach ($result->result() as $data) {
echo '<tr>';
echo '<td>'.$i++.'</td>';
echo '<td>'.$data->file_name.'</td>';
echo '<td>'.img('upload/'.$data->file_name).'</td>';
echo '</tr>';
}
} else {
echo '<tr>';
echo '<td colspan="3">Empty</td>';
echo '</tr>';
}
?>
</table>
</body>
</html>
Step 6
Open file config.php. /application/config/config.php
<?php $config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && ! in_array(strtolower($_SERVER['HTTPS']), array( 'off', 'no' ))) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/<your_project_name>';
Step 7
Open file routes.php. /application/config/routes.php
<?php $route['default_controller'] = 'image_upload';
Step 8
Create folder : upload
<your_project_name>/upload
0 comments:
Post a Comment