How to Upload Image in Codeigniter with Dropify Style [FULL TUTORIAL]

How to Upload Image in Codeigniter with Dropify Style [FULL TUTORIAL]

Giving style to the input file is a pretty hard thing to do.

If you are a beginner, of course this becomes a nightmare for you.

Good news,

Today, in this tutorial, I will share to you how to create upload image using codeigniter with dropify's style in input file.

So that, image can be preview before upload.

Awesome right?

In this tutorial, I will use Dropify to give style to the input file.

What is Dropify?

Dropify is a plugin css and javascript file to provide style to the input file and allowing user to select image you want to upload just by click drag and drop.

Pretty cool right?

So that, user interface can be more user friendly.

Dropify need jquery to run. So, we need jquery for this tutorial.

Besides jquery, we also need bootstrap to make user interface look better.

Ok, Let’s get start it!

First of all, we need to download Dropify, Jquery, Bootstrap, and Codeigniter.

After that, follow this step-by-step.

 

Step 1. Creating of database structure

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 name 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 name upload_db.

After that,

Create a table with name gallery with structure like this:

Database Structures

To create a table with structure like that,

You can execute this query:

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

 

Step 2. Setup Codeigniter

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 dropify_upload.

Like this:

Web Root

Open dropify folder and create resources folder. And then include the bootstrap, dropify, and jquery files inside the resources folder.

After that, create new folder named uploads inside resources folder. This folder will use for upload path.

So that look like this:

Structure Project

 

Step 3. 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'] = '';

Set to be like this:

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

3. Database.php

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

application/config/database.php

like this:

Config 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
);

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 4. 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'); //load model upload model
		$this->load->library('upload'); //load library upload 
	}

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

	function do_upload(){
		$config['upload_path'] = './resources/uploads/'; //path folder
	    $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //Allowing types
	    $config['encrypt_name'] = TRUE; //encrypt file name 

	    $this->upload->initialize($config);
	    if(!empty($_FILES['filefoto']['name'])){

	        if ($this->upload->do_upload('filefoto')){

	            $data   = $this->upload->data();
	            $image  = $data['file_name']; //get file name
				$title	= $this->input->post('title');
				$this->upload_model->upload_image($title,$image);
				echo "Upload Successful";

			}else{
	            echo "Upload failed. Image file must be gif|jpg|png|jpeg|bmp";
	        }
	                 
	    }else{
			echo "Failed, Image file is empty.";
		}
				
	}
	

}

 

Step 5. 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 upload_image($title,$image){
		$data = array(
			'title' => $title,
			'file_name' => $image, 
			);
		$result=$this->db->insert('gallery',$data);
		return $result;
	}
}

 

Step 6. View

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

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>Product List</title>
	<link rel="stylesheet" type="text/css" href="<?php echo base_url().'resources/css/bootstrap.css'?>">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url().'resources/dropify/css/dropify.css'?>">
</head>
<body>
<div class="container">
	<!-- Page Heading -->
    <div class="row">
        <div class="col-6 offset-md-3">
            <form action="<?php echo site_url('upload/do_upload');?>" method="post" enctype="multipart/form-data">
              <div class="form-group">
                <label for="exampleInputEmail1">Title</label>
                <input type="text" class="form-control" name="title" placeholder="Title">
              </div>
    
              <div class="form-group">
                <label for="exampleInputFile">File input</label>
                <input type="file" class="dropify" name="filefoto" data-height="300">
                
              </div>

              <button type="submit" class="btn btn-primary">Upload</button>
            </form>
            
        </div>
    </div>
        
</div>


<script type="text/javascript" src="<?php echo base_url().'resources/js/jquery-3.2.1.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'resources/js/bootstrap.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'resources/dropify/js/dropify.js'?>"></script>

<script type="text/javascript">
	$(document).ready(function(){
		$('.dropify').dropify();
	});

</script>
</body>
</html>

Now, go ahead and access our custom page at http://localhost/dropify_upload/index.php/upload and you will see the final result like this:

Form Upload

Input title and drag and drop to select image. You will see preview image before upload.

like this:

Preview upload

And then, you can click upload button to upload image to server.

Awesome right?

So, that's it,

We've done it!

Don't worry, I won't leave you that soon, as we'll start dissecting each part of the code now.

We'll start with the model file models/Upload_model.php as that's something will be called from our controller methods.

There is one methods, upload_image.

It's used to save records to the gallery table in database.

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

Moving ahead, let's switch our attention to the controller file. Go ahead and grab the code of the constructor method.

function __construct(){
	parent::__construct();
	$this->load->library('upload'); //load library upload
	$this->load->model('upload_model'); //load model upload model
}

In order to use file upload in CodeIgniter, the first thing you need to do is to load the upload library. And we can do it by using $this->load->library('upload').

We've also loaded the model upload_model, by using $this->load->model(‘upload_model’);

Next, Go ahead and grab the code of the index method.

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

This method is heart of out controller. It's used to call to the view, upload_view.

Now, we're ready to go through the main method, do_upload method.

This methods will handle uploading file image to server.

function do_upload(){
$config['upload_path'] = './resources/uploads/'; //path folder
    	$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //Allowing types
    	$config['encrypt_name'] = TRUE; //encrypt file name 

	$this->upload->initialize($config);
	 if(!empty($_FILES['filefoto']['name'])){

	        if ($this->upload->do_upload('filefoto')){

	            $data   = $this->upload->data();
	            $image  = $data['file_name']; //get file name
				$title	= $this->input->post('title');
				$this->upload_model->upload_image($title,$image);
				echo "Upload Successful";

			}else{
	            echo "Upload failed. Image file must be gif|jpg|png|jpeg|bmp";
	        }
	                 
	}else{
		echo "Failed, Image file is empty.";
	}
				
}

Done.

Congratulations!

You did it. Now, you can create a upload application with dropify style file upload using codeigniter.

If you feel this tutorial is useful for you. Please share! Perhaps, this tutorial is useful also for your friend!

Thank you very much.

Download Source

Share:



Sponsorship:

Comments (12)

Candice Maple, 23 June 2018 21:56 -

Congratulations Admin mfikri.com You have been selected to access the Amazon Code. I’m talking about an incredible top secret system that is turning just a few lucky, every day people into millionaires with the help of one of the largest websites in the world. This offer is only available for a limited period of time so make sure you click the link below and get signed up immediately before someone else takes this opportunity. The Amazon Code - GUARANTEED: $500 - Your Online Job for mfikri.com Click Here To Watch The Private Video ==> http://bit.ly/GET_ACCESS_AZCode Regards, =============================================== - IF YOU DO NOT WANT TO RECEIVE THIS MESSAGE !! - SEND EMAIL WITH YOUR SITE THAT YOU DO NOT WANT TO BE CONTACTED ==> unsubscribe_your_site@mail.com &lt;== ===============================================

Patsy Clancy, 08 July 2018 17:09 -

Woow, complete information. thanks!

Al Ames, 12 July 2018 04:08 -

Awesome

Isabella Charles, 16 July 2018 20:03 -

Nice post. thanks

M Fikri, 01 August 2018 17:50 -

You're welcome

Edna Hornsby, 18 July 2018 05:14 -

Awesome post.

M Fikri, 01 August 2018 17:47 -

Thank you.

Jamila Rubin, 21 July 2018 14:04 -

Really helpful

Carrol Chamberlin, 24 July 2018 14:37 -

Nice post.

M Fikri, 01 August 2018 17:38 -

Thank You.

Rich Boucaut, 26 July 2018 16:30 -

I Believe The WORLD's need this. Good Stuff.

M Fikri, 01 August 2018 17:37 -

Thank You.

Leave a Comment