How to Upload files using Codeigniter and Ajax [Complete Tutorial]

How to Upload files using Codeigniter and Ajax [Complete Tutorial]

I think you'll agree if I say this:

"It is very difficult to create file upload with Codeigniter and AJAX Jquery."

The good news:

Well, it turns out, you can easily create file uploads with Codeigniter and AJAX Jquery. Right now!

In today's tutorial. You will learn everything you need to know about how to create upload files with Codeigniter and Ajax jquery, Step by step.

Let’s begin.

 

How do I find a simple way to upload files with Codeigniter and Ajax Jquery

Before I explain how to create upload files with codeigniter and ajax, let me tell you a short story.

A few months ago I was interested to create upload files with codeigniter and Ajax.

So that, I started surfing on google.

And then I found a very interesting article from tutsplus.com.

Here's a screenshot of the article:

Code Tutplus

Source: https://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684

At the first time I saw this article, I immediately wanted to try to apply it.

After I read it again, it turns out, he uses an additional library that is AjaxFileUpload.

But, I don't want to use the library AjaxFileUpload, and I try to find another way.

Because, I just want to use jquery, not something else.

And finally I decided to create upload files with codeigniter and ajax jquery without AjaxFileUpload library.

Apparently, without AjaxFileUpload library, It still easy to create upload files with ajax and codeigniter.

It's even easier to customize later on.

So, how to create upload files with Codeigniter and Ajax jquery without additional library?

Let’s get start it.

Most beginners have difficulty creating uploaded files with codeigniter and Ajax.

Most of you may have managed to create file uploads with codeigniter.

But, to create upload files with Codeigniter + Ajax Jquery face a lot of difficulties.

Here's the problem:

Most beginners have any problem to get value of the input file using Ajax Jquery.

It is because,

To submit form upload file in codeigniter has to use form_open_multipart.

Form_open_multipart only working if you create upload file without Ajax Jquery

But, if you want to use ajax jquery, You have to use FormData().

It may sound complicated, but it is not.

What is FormData?

How it work?

Here step by step how to create upload files with codeigniter and Ajax Jquery.

By following this tutorial step by step, You will immediately understand what is FormData and how it is work.

Stay tuned!

 

Step 1. Preparation

This is important!

If you missed this step, it means you missed the whole of this tutorial.

Good preparation will determine your success following this tutorial. The better your preparation, the more likely you will succeed in following this tutorial.

Do not skip this step, though it feels complex.

So, what do you need to prepare?

Here’s the list:

1. Codeiginter

Codeigniter is the main php framework we will use in this tutorial. If you do not have it yet, please download it at the official website: www.codeigniter.com

2. Bootstrap

Bootstrap is a framework to beautify the user interface (UI). If you do not have it yet, please download it first at the official website: www.getbootstrap.com

3. Jquery

This is important!

Jquery is a javascript library that works to help simplify the writing of AJAX-based scripts.

If you do not have it yet, please download it at the official website: www.jquery.com

Ok, Let's continue!

 

Step 2. Database preparation

In this tutorial, I use mysql as Database Management System (DBMS).

If you also use mysql, you will love this tutorial.

But,

If you are using other DBMS like Oracle, SQL Server, Maria DB, or MongoDB.

No, Problem!

Provided you understand SQL (Structured Query Language) better.

Ok, Let's continue!

Please create a database, here I create a database with named upload_db.

If you create a database with the same name it will be better.

Please execute this query to create the database:

CREATE DATABASE upload_db;

That query will generate a database with named upload_db.

After that,

Create a table with name gallery with structure like this:

Database Structure

To create a table structure like the picture above,

You could follow this query:

CREATE TABLE gallery(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100),
file_name VARCHAR(40)
)ENGINE=INNODB;

 

Step 3. Codeigniter Installation

Next,

Extract codeigniter that has been downloaded earlier to www folder (if you use wampserver) or htdocs (if you use XAMPP).

Because I use wampserver. So, I extract it to c:/wamp/www/

And then, rename codeigniter project to be ajax_upload.

Like this:

Web Root

Open the ajax_upload folder and create the assets folder parallel to the application and system folders, and then include the bootstrap and jquery files in the assets folder.

And then,

Create one more folder in the assets folder, and name it images.

Folder images serves to accommodate the image files that are uploaded later.

So, we see the structure of our project as follows:

Project Structure

In the picture above can be seen, that in the folder assets there are folder css, images, and js.

In the css folder, there is a bootstrap.css file.

In the js folder, there are bootstrap.js and jquery-3.2.1.js files.

 

Step 4. Codeigniter Configuration

Next step is the configuration on the codeigniter.

Here are some files you need to configure:

1. Autoload.php

To configure the autoload.php, please open the folder:

application/config/autoload.php

like this:

Autoload

Open autoload.php using text editor like Notepad++ or Sublime Text.

And then find this code:

$autoload['libraries'] = array();
$autoload['helper'] = array();

Set to be like this:

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

 

2. Config.php

To configure the config.php, please open the folder:

application/config/config.php

like this:

Config

Open config.php file using text editor, and then find this code:

$config['base_url'] = '';

And then set to be like this:

$config['base_url'] = 'http://localhost/ajax_upload/';

 

3. Database.php

To configure the database.php, please open the folder:

application/config/database.php

like this:

database

Open database.php file using text editor, and then find this code:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => '',
	'password' => '',
	'database' => '', 
	'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
);

And then Set to be like this:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'upload_db', 
	'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
);

 

Step 5. Controller

The controller serves as like a bridge between model and view.

The controller will respond HTTP requests coming from user (via browser), from this request the Controller will handle what to do.

It may sound a little bit complicated, but it is not.

You will understand soon after practicing the whole of this tutorial.

The controller will handle the process of uploading files to server and send the value (value) sent to model to be saved to database.

Ok, let’s create a controller!

Go ahead and create a controller file controllers/Upload.php with the following this code:

<?php
class Upload extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->load->model('upload_model');
	}

	function index(){
		$this->load->view('upload_view');
	}


	function do_upload(){
        $config['upload_path']="./assets/images";
        $config['allowed_types']='gif|jpg|png';
        $config['encrypt_name'] = TRUE;
        
        $this->load->library('upload',$config);
	    if($this->upload->do_upload("file")){
	        $data = array('upload_data' => $this->upload->data());

	        $title= $this->input->post('title');
	        $image= $data['upload_data']['file_name']; 
	        
	        $result= $this->upload_model->save_upload($title,$image);
	        echo json_decode($result);
        }

     }
	
}

Code Explanation:

This is important!

In the controller Upload.php, there are 3 methods. There are function __construct(), function index(), and function do_upload().

Let’s start from function __construct()

function __construct(){
	parent::__construct();
	$this->load->model('m_upload');
}

This method serves as a constructor, where each call of a model, library, helper, or whatever is called through the function __construct (), it will be ready for every function in a class.

In this case, you can see model upload_model is called in the function __construct ().

It mean, model upload_model is ready for every function in Upload class.

Let move to the function index() methods.

function index(){
	$this->load->view('upload_view');	
}

Function index is a function that is called automatically when in a file or class is calling.

In this case, the function index calls a view with name upload_view.

Next, function do_upload() methods.

function do_upload(){
        $config['upload_path']="./assets/images";
        $config['allowed_types']='gif|jpg|png';
        $config['encrypt_name'] = TRUE;
        
        $this->load->library('upload',$config);
	    if($this->upload->do_upload("file")){
	        $data = array('upload_data' => $this->upload->data());

	        $title= $this->input->post('title');
	        $image= $data['upload_data']['file_name']; 
	        
	        $result= $this->upload_model->save_upload($title,$image);
	        echo json_decode($result);
        }
}

This methods will handle the process of uploading files to server, as well as sending value name of file to model to save in database.

 

Step 6. Model

Go ahead and create a model file models/Upload_model.php with the following this code:

<?php
class Upload_model extends CI_Model{

	function save_upload($title,$image){
		$data = array(
	        	'title' 	=> $title,
	        	'file_name' => $image
	       	);  
	    $result= $this->db->insert('gallery',$data);
	    return $result;
	}

	
}

In Upload_model model there is one method. That is the save_upload method.

This method serves to store the value sent from the controller to be saved to the database.

 

Step 7. View

Next,

Go ahead and create a view file views/upload_view.php with the following this code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Upload files using Codeigniter and Ajax</title>
	<link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/bootstrap.css'?>">
</head>
<body>
	<div class="container">
		<div class="col-sm-4 col-md-offset-4">
		<h4>Upload files using Codeigniter and Ajax</h4>
			<form class="form-horizontal" id="submit">
				<div class="form-group">
					<input type="text" name="title" class="form-control" placeholder="Title">
				</div>
				<div class="form-group">
					<input type="file" name="file">
				</div>

				<div class="form-group">
					<button class="btn btn-success" id="btn_upload" type="submit">Upload</button>
				</div>
			</form>	
		</div>
	</div>
<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.2.1.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
<script type="text/javascript">
	$(document).ready(function(){

		$('#submit').submit(function(e){
		    e.preventDefault(); 
		         $.ajax({
		             url:'<?php echo base_url();?>index.php/upload/do_upload',
		             type:"post",
		             data:new FormData(this),
		             processData:false,
		             contentType:false,
		             cache:false,
		             async:false,
		              success: function(data){
		                  alert("Upload Image Successful.");
		           }
		         });
		    });
		

	});
	
</script>
</body>
</html>

This view serves to display a form to upload files.

This view also serves to submit the upload file form using AJAX.

If you notice in the script section, there is Ajax function.

As follows:

$('#submit').submit(function(e){
e.preventDefault(); 
		  $.ajax({
		             url:'<?php echo base_url();?>index.php/upload/do_upload',
		             type:"post",
		             data:new FormData(this), //this is formData
		             processData:false,
		             contentType:false,
		             cache:false,
		             async:false,
		              success: function(data){
		                  alert("Upload Image Successful.");
		           }
	         });
});

Done.

Open your browser, and visit the following url for testing:

http://localhost/ajax_upload/index.php/upload

Then it will appear form like this:

Form Upload

And then input Title and Browse file image want to upload.

After that, klik Upload button.

If running well, you will see alert success like this:

Success upload

To check the results of image files uploaded, please open the images folder in assets folder.

Like this:

Image Folder

Done!

Congratulations, you have successfully created a file upload with codeigniter and ajax.

But Wait.!!!

I will not leave you soon, let's explore the customize.

This is important!!!

 

Compress and Resize Image

Compress and resize the image when uploading is a very important thing you need to know.

By compressing and resizing the image can improve the speed, uniformity of image dimensions, and more user friendly.

So, how to compressing and resizing image when uploading?

Let’s begin.

Open the controller Upload.php, and then change function do_upload to be like this:

function do_upload(){
        $config['upload_path']="./assets/images";
        $config['allowed_types']='gif|jpg|png';
        $config['encrypt_name'] = TRUE;
        
        $this->load->library('upload',$config);
	    if($this->upload->do_upload("file")){
	        $data = $this->upload->data();

	        //Resize and Compress Image
            $config['image_library']='gd2';
            $config['source_image']='./assets/images/'.$data['file_name'];
            $config['create_thumb']= FALSE;
            $config['maintain_ratio']= FALSE;
            $config['quality']= '60%';
            $config['width']= 600;
            $config['height']= 400;
            $config['new_image']= './assets/images/'.$data['file_name'];
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();

	        $title= $this->input->post('title');
	        $image= $data['file_name']; 
	        
	        $result= $this->upload_model->save_upload($title,$image);
	        echo json_decode($result);
        }

}

Done.

That's it!

Open your browser, and visit the following url for testing:

http://localhost/ajax_upload/index.php/upload

And then, upload new image and klik upload button to upload.

After that go to images folder (assets/images) and check properties image you just upload.

Like this:

Resize Image Result

See, the image smaller than before.

Awesome right?

Alright, we have done it.

If you love this tutorial. Please share, perhaps your friend also need it.

Thank you so much.

Download Source

Share:



Sponsorship:

Comments (7)

naz jonson, 14 March 2018 14:03 -

We have update list of do-follow blog commenting sites for new visitors, we will update this list regular basis so share our list to your friends also. <a href="http://www.sthint.com/2017/11/17/100-instant-approval-free-dofollow-blog-commenting-sites-list-2018/">the bookmarking sites</a>

Lewis, 30 May 2018 06:21 -

Nice content, thank you!

M Fikri, 22 July 2018 08:43 -

Thank You.

aishwarya, 14 June 2018 18:54 -

No for me... not uploading image in directory

M Fikri, 22 July 2018 08:45 -

You can download the source code, Try it, and learn from that.!

Mitesh, 30 July 2018 20:22 -

thank you

M Fikri, 01 August 2018 17:29 -

You are welcome.

Leave a Comment