Codeigniter 4 Ajax Image Upload and Preview Tutorial

File uploading is a must-have feature in almost every web application; it becomes more subtle when you add an image to preview in it. This quick Codeigniter 4 Ajax File Upload tutorial will teach you how to create image upload and preview functionality in Codeigniter 4 app using the JavaScript AJAX.

We will respectively and gradually show you the small instructions which will address every programming aspect of building Ajax image upload in Codeigniter. We will show you how to use AJAX to handle file upload in the Codeigniter environment comprehensively.

Why use AJAX in Codeigniter? This Codeigniter AJAX image upload example focuses on making the request to the server and receiving and handling the response without reloading the entire web page. As per the common notion for this type of circumstances, AJAX is the best technique.

How to Upload Image and Show Preview in Codeigniter 4 using Ajax

  • Step 1: Download Codeigniter Project
  • Step 2: Create Uploads Table
  • Step 3: Connect with Database
  • Step 4: Turn On Error Handling
  • Step 5: Create Image Upload Controller
  • Step 6: Register New Route
  • Step 7: Set Up CI View
  • Step 8: Start CI Application

Download Codeigniter Project

Downloading Codeigniter app is doesn’t require intense efforts, you can download it with a single command if you have set up Composer or you can download the Codeigniter 4 app from the official site as well.

composer create-project codeigniter4/appstarter

Create Table with SQL Query

Subsequently, you have to run the SQL command to produce a profile table in the database, and this table will dynamically store all the uploaded images information.

CREATE TABLE profile (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    title varchar(100) NOT NULL COMMENT 'Title',
    file varchar(255) NOT NULL COMMENT 'File Type',
    created_at varchar(20) NOT NULL COMMENT 'Date Created',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Profile Table' AUTO_INCREMENT=1;

Connect with Database

A database connection is the need of the hour, move inside the app/Config/Database.php, add database name, username, and password to connect Codeigniter to MySQL database.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Turn On Error Handling

The Codeigniter’s error handling is by default turned off, however you can turn it on by changing display_errors variables value to 1, you have to do it this setting in app/Config/Boot/production.php.

ini_set('display_errors', '1');

Create Image Upload Controller

Get to the Controllers directory and create ImageUploadController file, a controller contains the single class with various functions to handle the specific functionality.

Create two functions, these methods will manage the view and image upload using the AJAX, insert the provided code into the app/Controllers/ImageUploadController.php.

<?php 

namespace App\Controllers;

use CodeIgniter\Controller;


class ImageUploadController extends Controller
{

    public function index() {
      return view('file_upload');
    }

    public function store()
    {  
      helper(['form', 'url']);
         
      $db = \Config\Database::connect();
      $builder = $db->table('profile');

      $isValid = $this->validate([
          'userfile' => [
              'uploaded[userfile]',
              'mime_in[userfile, image/jpg,image/jpeg,image/gif,image/png]',
              'max_size[userfile, 4098]',
          ],
      ]);
  
      $response = [
          'success' => false,
          'data' => '',
          'msg' => "Error occured"
      ];

      if ($isValid) {
          $file = $this->request->getFile('userfile');
          $file->move(WRITEPATH . 'uploads');

          $data = [
              'title' => $file->getClientName(),
              'file'  => $file->getClientMimeType()
          ];
          $save = $builder->insert($data);
          $response = [
              'success' => true,
              'data' => $save,
              'msg' => "File has uploaded  successfully!"
          ];
      }

      return $this->response->setJSON($response);
    }      

}

The getFile() function has the resilience to retrieves the file instance pass the file input name in the function. Validation can be added using the validate() functions; added the following validation rules for the image upload module.

  • The file exceeds the upload limit.
  • The file was only partially uploaded.
  • No file was uploaded.
  • The file could not be written on a disk.
  • The file could not be uploaded: missing temporary directory.

Register New Route

Further, you require to register the route in the app/Config/Routes.php; this route will give you the url that you can use to open the app in the browser.

At the same time it will invoke the controller index() function and load the file upload view template.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->get('/upload-file', 'ImageUploadController::index');

Create File Upload View

A view file is used to create the view of the feature we are working on, for instance in this step you have to create the file_upload.php file in the Views directory.

After that head over to app/Views/file_upload.php and place the code in within the file.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>Codeigniter 4 Ajax File Upload Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <div class="container">
        <form method="post" id="image_form" enctype="multipart/form-data">
            <div id="statusMessage" class="alert alert-info mb-2" style="display: none">
                <span id="statusMsg"></span>
            </div>

            <div class="d-grid text-center">
               <img class="mb-2" id="imgFileUpload" alt="Image preview" src="https://via.placeholder.com/400" />
            </div>

            <div class="form-group mb-2">
                <input type="file" name="userfile" id="file" multiple="true" onchange="onImageUpload(this);"
                    class="form-control" accept="image/*">
            </div>

            <div class="form-group">
               <button type="submit" class="btn btn-dark imgUploadButton">Upload Image</button>
            </div>
        </form>
    </div>

    <script>
        function onImageUpload(input, id) {
            id = id || '#imgFileUpload';
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $(id).attr('src', e.target.result).width(400)
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
        $(document).ready(function () {
            $('#image_form').on('submit', function (e) {

                $('.imgUploadButton').html('Uploading ...');
                $('.imgUploadButton').prop('Disabled');

                e.preventDefault();
                if ($('#file').val() == '') {
                    $('.imgUploadButton').html('Uploading ...');
                    $('.imgUploadButton').prop('enabled');
                    document.getElementById("image_form").reset();
                } else {
                    $.ajax({
                        url: "<?php echo base_url(); ?>/ImageUploadController/store",
                        method: "POST",
                        data: new FormData(this),
                        processData: false,
                        contentType: false,
                        cache: false,
                        dataType: "json",
                        success: function (res) {
                            console.log(res)
                            if (res.success == true) {
                                $('#imgFileUpload').attr('src', 'https://via.placeholder.com/400');
                                $('#statusMsg').html(res.msg);
                                $('#statusMessage').show();
                            } else if (res.success == false) {
                                $('#statusMsg').html(res.msg);
                                $('#statusMessage').show();
                            }
                            setTimeout(function () {
                                $('#statusMsg').html('');
                                $('#statusMessage').hide();
                            }, 5000);

                            $('.imgUploadButton').html('Upload');
                            $('.imgUploadButton').prop('Enabled');
                            document.getElementById("image_form").reset();
                        }
                    });
                }
            });
        });
    </script>
</body>

</html>

Start CI Application

Start the Codeigniter application using the suggested command, and it will let you test the feature on the browser.

php spark serve
http://localhost:8080/upload-file

Codeigniter Ajax Image Upload and Preview

Conclusion

We have looked at how to upload images in Codeigniter, alternatively how to show image preview after uploading using AJAX; this tutorial also addressed how to interact with the database and store images in the database after upload.

So, this was it; Codeigniter 4 image upload after preview tutorial is over.