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


Comments (23)

Jamila Rubin, 21 July 2018 14:04 -

Really helpful

M Fikri, 20 October 2018 08:47 -

Thank you.

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.

Krystyna Nanson, 15 October 2018 18:58 -

Really helpful, thank you.

M Fikri, 20 October 2018 08:47 -

You're Welcome.

Maroof Khan, 04 April 2019 18:03 -

Great work By M FIKRI

Mikki Wimmer, 30 June 2019 13:14 -

Awesome post, Thanks

Leave a Comment