AJAX Multiple Files Upload using Codeigniter, jQuery

Introduction

I will show you how to upload multiple files using Codeigniter, AJAX and jQuery without page refresh. This multiple files upload tutorial example is very helpful to implement the upload functionality. In this example the files are selected using the browse button and files are uploaded to the ‘uploads’ directory. Codeigniter controller stores files into the defined location and returns response as success or failure messages from the controller. As a validation step I have added only to check if you have selected a file for uploading or not.

You may read also AJAX File Upload using Codeigniter, jQuery, AJAX Multiple Files Upload using PHP, jQuery and  AJAX File Upload using PHP, jQuery

Prerequisites

Apace 2.4
PHP 7.0.15
Codeigniter 3.1.10

Example with Source Code

Creating Project Directory

Create a project ditectory called codeigniter-3.1.10-jquery-ajax-multiple-file-upload under <apache server installation directory>/htdocs. We will also create a directory called uploads that will hold all uploaded files.

Configuring Auto-load

Now modify codeigniter-3.1.10-jquery-ajax-multiple-file-upload/application/config/autoload.php file for auto-loading html, url, file, form.

$autoload['helper'] = array('html', 'url', 'file', 'form');

Creating Controller Class

Create a controller file AjaxMultipleFileUpload.php under
codeigniter-3.1.10-jquery-ajax-multiple-file-upload/application /application/controllers with the following source code

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of ajaxupload
 *
 * @author https://roytuts.com
 */
class AjaxUpload extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $this->load->view('files_upload_ajax', NULL);
    }

    function upload_files() {
        if (isset($_FILES['files']) && !empty($_FILES['files'])) {
            $no_files = count($_FILES["files"]['name']);
            for ($i = 0; $i < $no_files; $i++) {
                if ($_FILES["files"]["error"][$i] > 0) {
                    echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
                } else {
                    if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
                        echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
                    } else {
                        move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
                        echo 'File successfully uploaded : uploads/' . $_FILES['files']['name'][$i] . ' ';
                    }
                }
            }
        } else {
            echo 'Please choose at least one file';
        }
    }

}

Creating View

Create a view file files_upload_ajax.php under codeigniter-3.1.10-jquery-ajax-multiple-file-upload/application/views.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>AJAX File upload using Codeigniter, jQuery</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function (e) {
                $('#upload').on('click', function () {
                    var form_data = new FormData();
                    var ins = document.getElementById('multiFiles').files.length;
                    for (var x = 0; x < ins; x++) {
                        form_data.append("files[]", document.getElementById('multiFiles').files[x]);
                    }
                    $.ajax({
                        url: 'http://localhost/ci3/index.php/ajaxupload/upload_files', // point to server-side controller method
                        dataType: 'text', // what to expect back from the server
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the server
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the server
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="msg"></p>
        <input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
        <button id="upload">Upload</button>
    </body>
</html>

Configuring Route

Modify file codeigniter-3.1.10-jquery-ajax-multiple-file-upload/application/config/routes.php file.

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

Testing the Application

If everything is fine then run the application by hitting the URL . You will get the output in the browser.

ajax multiple files upload using codeigniter jquery

If you try to upload file without selecting any file then you would see error message “Please select at least one file”.

ajax multiple files upload using codeigniter jquery

If the file successfully uploaded then you will see success message “File successfully uploaded : uploads/<some-file-name>“.

ajax multiple files upload using codeigniter jquery
ajax multiple files upload using codeigniter jquery

If the file you are trying to upload already exists then you will see a message “File already exists : uploads/<some-file-name>“.

Hope you have got an idea how to upload multiple files using Codeigniter, AJAX and jQuery.

Source Code

You can download source code.

Thanks for reading.

AJAX Multiple Files Upload using Codeigniter, jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top