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/7.4.3, Codeigniter 3.1.10/3.1.11, jQuery 3.4.1/3.5.1

Make sure you create a folder uploads under your project root directory to store your uploaded files.

Project Directory

Create a project ditectory called codeigniter-jquery-ajax-multiple-file-upload under <apache server installation directory>/htdocs.

I will also create a directory called uploads under project root directory, where file will be uploaded.

I may not mention the project root directory in subsequent sections but I will assume that I am 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');

Controller Class

Create a controller file AjaxMultipleFileUpload.php under
/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';
        }
    }

}

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 src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></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-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-jquery-ajax-multiple-file-upload. You will get the output in the browser as shown in the below image:

ajax multiple files upload codeigniter jquery ajax

If you try to upload file without selecting any file then you would see error message – Please choose at least one file.

ajax multiple files upload codeigniter jquery ajax

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

ajax multiple files upload using codeigniter jquery ajax

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

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

Source Code

Download

Leave a Reply

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