Drag and Drop file upload with Dropzone in CodeIgniter

Dropzone is a JavaScript library which allows uploading file by drag’n’drop and display the file preview after upload.

It is easier to add to the page and it does not depend on any library like jQuery.

The file will upload to the server via AJAX.

In this tutorial, I show how you can use the Dropzone library to upload the file in CodeIgniter.

Drag and Drop file upload with Dropzone in CodeIgniter


Contents

  1. Default controller
  2. Controller
  3. View
  4. Demo
  5. Conclusion

1. Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

2. Controller

Create a new User.php file in application/controllers/ directory and also create a uploads directory at project root to store files.

Drag and Drop file upload with Dropzone in CodeIgniter

Create 3 methods –

  • __construct() – Load URL helper.
  • index() – Load user_view view.
  • fileUpload() – This method is called when a file is a drag and drop on the dropzone container to upload a file. Here, set the upload preference –  upload path, allowed type, max file size, and file name.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

  public function __construct(){

    parent::__construct();
    $this->load->helper('url');

  }

  public function index(){

    // load view
    $this->load->view('user_view');

  }

  // File upload
  public function fileUpload(){

   if(!empty($_FILES['file']['name'])){

     // Set preference
     $config['upload_path'] = 'uploads/'; 
     $config['allowed_types'] = 'jpg|jpeg|png|gif';
     $config['max_size'] = '1024'; // max_size in kb
     $config['file_name'] = $_FILES['file']['name'];

     //Load upload library
     $this->load->library('upload',$config); 

     // File upload
     if($this->upload->do_upload('file')){
       // Get data about the file
       $uploadData = $this->upload->data();
     }
   }

 }

}

3. View

Create a new user_view.php file in application/views/ directory.

Download & Include

  • Download Dropzone from here and create a resources directory at project root to store dropzone.js and dropzone.css files.

Drag and Drop file upload with Dropzone in CodeIgniter

  • Include dropzone.js and dropzone.css in <head> section.

HTML

Just need to create a <form action = "<?= base_url('index.php/User/fileupload') ?>" class= "dropzone" id="fileupload">. When a page is run this will add a container for upload files by drag & drop.

Script

Use Dropzone.options to allow only image files and set the max file size to 1 MB. Here, fileupload is the id of <form>.

Dropzone.options.fileupload = { acceptedFiles: 'image/*', maxFilesize: 1 // MB };

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
  <head> 
    
    <!-- Dropzone CSS & JS -->
    <link href='<?= base_url() ?>resources/dropzone.css' type='text/css' rel='stylesheet'>
    <script src='<?= base_url() ?>resources/dropzone.js' type='text/javascript'></script>
    
    <!-- Dropzone CDN -->
    <!-- 
    <link href='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.css' type='text/css' rel='stylesheet'>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js' type='text/javascript'></script>
    -->
    <style>
    .content{
      width: 50%;
      padding: 5px;
      margin: 0 auto;
    }
    .content span{
      width: 250px;
    }
    .dz-message{
      text-align: center;
      font-size: 28px;
    }
    </style>
    <script>
    // Add restrictions
    Dropzone.options.fileupload = {
      acceptedFiles: 'image/*',
      maxFilesize: 1 // MB
    };
    </script>
  </head>
  <body>

    <div class='content'>
      <!-- Dropzone -->
      <form action="<?= base_url('index.php/User/fileupload') ?>" class="dropzone" id="fileupload">
      </form> 
    </div> 

  </body>
</html>

4. Demo

Try to upload different types of file. Open in a new tab then click here.

NOTE – Only image files will upload and max size will be 1 MB.


5. Conclusion

With only <form > you can add dropzone on your webpage. Whenever a file is dragged then it will send an AJAX request to <form > action URL for file upload.

Modify file restriction for the Dropzone according to your requirement in the <script > you can find more about here and also in the controller file.

If you found this tutorial helpful then don't forget to share.

15 thoughts on “Drag and Drop file upload with Dropzone in CodeIgniter”

  1. sir.. i follow u tutorial , but i got error when i modifed in my config and then i change csrf token to be TRUE
    can u help me? to resolved my error please…

    Reply
      • can you help me how to resolved my problem..

        this is my controller
        function proses_upload(){
        $config[‘upload_path’] = FCPATH.’/upload-foto/’;
        $config[‘allowed_types’] = ‘gif|jpg|png|ico’;
        $this->load->library(‘upload’,$config);

        if($this->upload->do_upload(‘userfile’)){
        $token=$this->input->post(‘token_foto’);
        $nama=$this->upload->data(‘file_name’);
        $this->db->insert(‘foto’,array(‘nama_foto’=>$nama,’token’=>$token));
        }
        }

        function remove_foto(){
        $token=$this->input->post(‘token’);
        $foto=$this->db->get_where(‘foto’,array(‘token’=>$token));

        if($foto->num_rows()>0){
        $hasil=$foto->row();
        $nama_foto=$hasil->nama_foto;
        if(file_exists($file=FCPATH.’/upload-foto/’.$nama_foto)){
        unlink($file);
        }
        $this->db->delete(‘foto’,array(‘token’=>$token));
        }
        echo “{}”;
        }

        this is my js

        Dropzone.autoDiscover = false;
        var foto_upload= new Dropzone(“.dropzone”,{
        url: “”,
        maxFilesize: 2,
        method:”post”,
        acceptedFiles:”image/*”,
        paramName:”userfile”,
        dictInvalidFileType:”Type file ini tidak dizinkan”,
        addRemoveLinks:true,
        });

        foto_upload.on(“sending”,function(a,b,c){
        a.token=Math.random();
        c.append(“token_foto”,a.token);
        });

        foto_upload.on(“removedfile”,function(a){
        var token=a.token;
        $.ajax({
        type:”post”,
        data:{token:token},
        url:””,
        cache:false,
        dataType: ‘json’,
        success: function(){
        console.log(“Foto terhapus”);
        },
        error: function(){
        console.log(“Error”);

        }
        });
        });

        this is my view

        Klik atau Drop gambar disini

        i’m realy 2 thank you when you help me to resolved my problem

      • You can try this code –

        var csrf_test_name = “<?php echo $this->security->get_csrf_hash(); ?>”;
        var myDropzone = new Dropzone(“#fileupload”);
        myDropzone.on(“sending”, function(file, xhr, formData) {

        formData.append(“csrf_test_name”, csrf_test_name);
        });

        I tested it. It is working.

    • Hello @karthik , even im facing the same problem. If u resolved the issue kindly share the response.. thanks in advance.

      Reply
    • the files are not uploading it is giving the error servrer responded with 0 code..please can u help me with it asap….thanks in advance.

      Reply
  2. the files are not uploading it is giving the error servrer responded with 0 code..please can u help me with it asap….thanks in advance.

    Reply

Leave a Comment