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.

Related Posts:

Prerequisites

Apace HTTP Server 2.4
PHP 7.3.5, Codeigniter 3.1.10, jQuery

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 under project root directory, where file will be uploaded.

We may not mention the project root directory in subsequent sections but we will assume that we are creating files or folders with respect to the project root directory.

Configuring Auto-load

Now modify 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
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 AjaxMultipleFileUpload 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 application/views directory.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>AJAX File upload using Codeigniter, jQuery</title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.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/codeigniter-3.1.10-jquery-ajax-multiple-file-upload/index.php/ajaxmultiplefileupload/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 application/config/routes.php file to configure the default controller that will be called upon context root access of the application.

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

Testing the Application

If everything is fine then run the application by hitting the URL http://localhost/codeigniter-3.1.10-jquery-ajax-multiple-file-upload/index.php. You will get the output in the browser as shown in the below image:

ajax multiple files upload codeiniter 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 codeiniter 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

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

download source code

Thanks for reading.

Related posts

Leave a Comment