In this tutorial we imaplementing simple image uploading and inserting record into database in codeigniter. the codeigniter provide default file uploading function. Image uploading basic operation in each website. this implementation we use ajax for fast uploading and without effect website load.
Create database tables:
CREATE TABLE `photo` (
`id` int(11) NOT NULL,
`photo_name` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Database Configuration (Application/config/database.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'upload',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Controllers (Application/controllers/File_upload.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class File_upload extends CI_Controller {
public function index()
{
$this->load->view('layout/index');
}
public function uploading()
{
# code...
$newFilename = time() . "_" . $_FILES["file"]["name"];
$location = 'upload/' . $newFilename;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
$fname['photo_name']=$newFilename;
$this->Data_model->insert_photo_name($fname);
}
public function fetch_photo()
{
$response='';
$result1= $this->Data_model->all_photo();
# code...
foreach ($result1 as $value1) {
# code...
$photo_location='upload/'.$value1->photo_name;
$response.= '<div class="col-lg-3"><img src="'. $photo_location.'" style="height:200px; width:100%;"></div>';
}
echo $response;
}
}
View (Application/views/layout/index.php)
<!DOCTYPE html>
<html>
<head>
<title>Image Upload using AJAX in codeigniter with database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div style="height:50px;"></div>
<div class="row">
<div style="width:50%; padding:auto; margin:auto">
<form>
<h2 align="center" style="color:red">Image Upload using AJAX in codeigniter with database</h2>
<label>Select Image:</label>
<input type="file" name="file" id="file"><br>
<button type="button" id="upload_button" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
<div style="height:50px;"></div>
<div style="width:80%; padding:auto; margin:auto;">
<div id="image_box" class="wall">
</div>
</div>
</div>
</body>
</html>
JavaScript code
<script type="text/javascript">
$(document).ready(function(){
showPhoto();
$(document).on('click', '#upload_button', function(){
var name = document.getElementById("file").files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1){
alert("Invalid Image File");
}
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000){
alert("Image File Size is very big");
}
else{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax({
url:"<?php echo base_url('File_upload/uploading')?>",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(){
showPhoto();
}
});
}
});
});
function showPhoto(){
$.ajax({
url:"<?php echo base_url('File_upload/fetch_photo');?>",
method:"POST",
data:{
fetch:1,
},
success:function(data){
$('#image_box').html(data);
}
});
}
</script>