Introduction

I will show you an example on Ajax file upload using Codeigniter jQuery without page refresh. This file upload tutorial example is very helpful to implement the upload functionality. In this example the file is selected using the browse button and file is uploaded to the uploads directory. Codeigniter controller stores the file into the specified location and returns response as a success or failure message from the controller. As a validation step I have checked if end users have selected a file for uploading or not.

Related Posts:

Prerequisites

PHP 7.3.5
Apache HTTP Server 2.4
Codeigniter 3.1.10, jQuery

Example with Source Code

Creating Project Directory

A typical directory structure for the project Ajax file upload using Codeigniter jQuery would be by creating a project directory called codeigniter-3.1.10-jquery-ajax-file-upload.

We will create another directory called uploads directory under project directory which will contain all uploaded files.

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

Configuring Auto-load

Now modify application/config/autoload.php file for auto-loading html, url, file, form.

This is one time activity and once you load you can use uniformly throughout the application code.

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

Creating Controller Class

Create a controller file AjaxFileUpload.php under application/controllers folder with the following source code.

This controller class is responsible for handling request and response of clients and any validation or business logic as applicable.

<?php

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

/**
 * Description of AjaxFileUpload
 *
 * @author https://www.roytuts.com
 */
class AjaxFileUpload extends CI_Controller {

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

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

    function upload_file() {

        //upload file
        $config['upload_path'] = 'uploads/';
        $config['allowed_types'] = '*';
        $config['max_filename'] = '255';
        $config['encrypt_name'] = TRUE;
        $config['max_size'] = '1024'; //1 MB

        if (isset($_FILES['file']['name'])) {
            if (0 < $_FILES['file']['error']) {
                echo 'Error during file upload' . $_FILES['file']['error'];
            } else {
                if (file_exists('uploads/' . $_FILES['file']['name'])) {
                    echo 'File already exists : uploads/' . $_FILES['file']['name'];
                } else {
                    $this->load->library('upload', $config);
                    if (!$this->upload->do_upload('file')) {
                        echo $this->upload->display_errors();
                    } else {
                        echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
                    }
                }
            }
        } else {
            echo 'Please choose a file';
        }
    }

}

Creating View

Create a view file file_upload_ajax.php under application/views directory. Here we have shown how to use ajax file upload using codeigniter jquery.

This file is responsible for giving user options to select and upload file.

The below view file has one input button for file type and another button for submission once the file is selected for uploading.

Then we catch the button’s onClick event through jQuery and upload the file at appropriate destination in the server location.

Finally we display either success or failure message as we receive from the server through success or error methods respectively.

<!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 file_data = $('#file').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: 'http://localhost/codeigniter-3.1.10-jquery-ajax-file-upload/index.php/ajaxfileupload/upload_file', // 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="file" name="file" />
        <button id="upload">Upload</button>
    </body>
</html>

Configuring Route

Modify file application/config/routes.php file because we want our above controller class to be default to load the view file for uploading file.

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

Testing the Application

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

ajax file upload using codeigniter jquery

If you try to upload file without selecting any file then you would see error message “Please choose a file“.

ajax file upload using codeigniter jquery

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

ajax file 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 on ajax file upload file using Codeigniter jQuery.

Source Code

Thanks for reading.

Tags:

7 thoughts on “AJAX File Upload using Codeigniter, jQuery

Leave a Reply

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