Drag and Drop File Upload with Dropzone in Codeigniter

Drag and Drop upload provides a user-friendly way to upload files to the server. Generally, the user selects files from the local drive to upload. But with the Drag&Drop feature, the user can drag files from local drive and drop them to the HTML element for upload. You can use the drag and drop upload feature in the web application to implement the file upload functionality.

DropzoneJS is an open-source JavaScript library that provides an easy way to implement drag & drop file upload functionality with image preview. It attached the drag and drop event to the normal HTML form that makes it droppable. The DropzoneJS library doesn’t depend on any other library, you can use it without using jQuery also. The drag and drop files upload functionality can be easily integrated with Dropzone and PHP.

If your web application is developed with CodeIgniter and wants to upload multiple files or images, this functionality can be implemented with Dropzone. In this tutorial, we will show you how to integrate drag and drop file upload in CodeIgniter using DropzoneJS.

In the example code, the following functionality will be implemented to upload multiple files with drap & drop feature in CodeIgniter.

  • Allow users to drag and drop multiple files to upload.
  • Upload multiple files to the server using CodeIgniter’s Upload library.
  • Store file data in the MySQL database.
  • Retrieve files/images from the database and display them on the web page.

Before getting started, take a look at the file structure of the sample CodeIgniter Drag & Drop File Upload application.

codeigniter_drag_drop_file_upload/
├── application/
│   ├── controllers/
│   │   └── Upload_file.php
│   ├── models/
│   │   └── File.php
│   └── views/
│       └── upload_file/
│           └── index.php
│── assets/
│   ├── js/
│   │   └── dropzone/
│   │       │── dropzone.min.js
│   │       └── dropzone.min.css
│   └── css/
│       └── style.css
│
└── uploads/

Create Database Table

To store the file information, a table is required in the database. The following SQL creates a files table with some basic fields in the MySQL database.

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create Upload Folder

To store the files, a directory is required on the server. Create a folder (uploads/) in the root folder of the CodeIgniter application where you want to store the uploaded files.

Controller (Upload_file.php)

The Upload_File controller handles the multiple files upload functionality.

  • __construct()
    • Loads File model that helps to insert file info into the database and fetch files data from the database.
  • index()
    • Fetch all images from the database using the getRows() method of the File model.
    • Pass files data to the view.
  • dragDropUpload()
    • Set preferences (upload path, allowed types, etc), load and initialize the Upload library.
    • Upload files to the server using the do_upload() function of the Upload library.
    • Insert the file data in the database using the insert() method of the File model.
<?php 
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Upload_File extends CI_Controller {
    function  
__construct() {
        
parent::__construct();
        
        
// Load file model
        
$this->load->model('file');
    }
    
    function 
index(){
        
$data = array();
        
        
// Get files data from the database
        
$data['files'] = $this->file->getRows();
        
        
// Pass the files data to view
        
$this->load->view('upload_file/index'$data);
    }
    
    function 
dragDropUpload(){
        if(!empty(
$_FILES)){
            
// File upload configuration
            
$uploadPath 'uploads/';
            
$config['upload_path'] = $uploadPath;
            
$config['allowed_types'] = '*';
            
            
// Load and initialize upload library
            
$this->load->library('upload'$config);
            
$this->upload->initialize($config);
            
            
// Upload file to the server
            
if($this->upload->do_upload('file')){
                
$fileData $this->upload->data();
                
$uploadData['file_name'] = $fileData['file_name'];
                
$uploadData['uploaded_on'] = date("Y-m-d H:i:s");
                
                
// Insert files info into the database
                
$insert $this->file->insert($uploadData);
            }
        }
    }
}

Model (File.php)

The File model handles the database related operations (fetch and insert).

  • __construct() – Define the table name where the files data will be stored.
  • getRows()
    • Fetch the file data from the database.
    • Returns a single record if the ID is specified, otherwise all records.
  • insert()
    • Insert file data into the database using the insert() function of CodeIgniter Query Builder Class.
<?php  
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
File extends CI_Model{
    function 
__construct() {
        
$this->tableName 'files';
    }
    
    
/*
     * Fetch files data from the database
     * @param id returns a single record if specified, otherwise all records
     */
    
public function getRows($id ''){
        
$this->db->select('id,file_name,uploaded_on');
        
$this->db->from('files');
        if(
$id){
            
$this->db->where('id',$id);
            
$query $this->db->get();
            
$result $query->row_array();
        }else{
            
$this->db->order_by('uploaded_on','desc');
            
$query $this->db->get();
            
$result $query->result_array();
        }
        
        return !empty(
$result)?$result:false;
    }
    
    
/*
     * Insert file data into the database
     * @param array the data for inserting into the table
     */
    
public function insert($data = array()){
        
$insert $this->db->insert('files'$data);
        return 
$insert?true:false;
    }
}

View (upload_file/index.php)

Include the CSS & JS file of the DropzoneJS library.

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/js/dropzone/dropzone.min.css" />
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/dropzone/dropzone.min.js"></script>

Create a form element and add a class attribute with dropzone.

  • The action attribute of the <form> tag defines the action to perform the server-side upload.
  • The dropzone class is an identifier of the Dropzone library.
  • Dropzone will attach to this form element and the dropped files are posted to the dragDropUpload() method of the Upload_File controller.
<form action="<?php echo base_url('upload_file/dragDropUpload/'); ?>" class="dropzone"></form>

The uploaded files will be listed under the Drag&Drop form element.

  • The <embed> tag is used to display all types of files (image, pdf, word, video, etc.) on the web page.
<?php 
if(!empty($files)){ foreach($files as $row){
        
$filePath 'uploads/'.$row["file_name"];
        
$fileMime mime_content_type($filePath);
?>
    <embed src="<?php echo base_url('uploads/'.$row["file_name"]); ?>" type="<?php echo $fileMime?>" width="350px" height="240px" />
<?php
} }else{
?>
    <p>No file(s) found...</p>
<?php ?>

Upload Multiple Files and Images in CodeIgniter

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up