Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 Image Upload with Preview Tutorial

Last Updated on July 16, 2024 by

In CodeIgniter 4, the jQuery file reader function allows reading the image for preview before uploading it to the server.

Let’s start creating image upload with preview feature in CodeIgniter:

Step 1: Setting Up the Project

First, create a new CodeIgniter 4 project or navigate to your existing project directory.

Step 2: Create the Upload Form

Create a new file named upload_form.php in app/Views/ directory with the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload with Preview in CodeIgniter 4 - ItcodStuff.com</title>
    <style>
        .preview {
            width: 200px;
            height: 200px;
            border: 1px solid #ddd;
            display: none;
            margin-top: 10px;
        }
    </style>
</head>
<body>

<h2>Upload Image</h2>
<form method="POST" action="<?= base_url('upload') ?>" enctype="multipart/form-data">
    <input type="file" name="image" id="image">
    <div class="preview">
        <img id="preview-image" src="" alt="Preview" style="max-width: 100%; max-height: 100%;">
    </div>
    <br>
    <button type="submit">Upload</button>
</form>

<script>
    document.getElementById('image').addEventListener('change', function(event) {
        const [file] = this.files;
        if (file) {
            document.querySelector('.preview').style.display = 'block';
            document.getElementById('preview-image').src = URL.createObjectURL(file);
        } else {
            document.querySelector('.preview').style.display = 'none';
            document.getElementById('preview-image').src = '';
        }
    });
</script>

</body>
</html>

Step 3: Create the Controller

Create a new controller named Upload.php in app/Controllers/ directory with the following code that handle the image upload:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\Files\File;

class Upload extends Controller
{
    public function index()
    {
        return view('upload_form');
    }

    public function upload()
    {
        $validationRule = [
            'image' => [
                'label' => 'Image File',
                'rules' => 'uploaded[image]'
                    . '|is_image[image]'
                    . '|mime_in[image,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                    . '|max_size[image,4096]', // 4MB max
            ],
        ];

        if (!$this->validate($validationRule)) {
            return view('upload_form', [
                'validation' => $this->validator,
            ]);
        }

        $img = $this->request->getFile('image');
        if (!$img->hasMoved()) {
            $newName = $img->getRandomName();
            $img->move(WRITEPATH . 'uploads', $newName);

            echo "File uploaded successfully: " . $img->getName();
        } else {
            echo "The file has already been moved.";
        }
    }
}

Step 4: Define Routes

Edit app/Config/Routes.php file and define routes in it to display the upload form and handle the image upload:

$routes->get('/', 'Upload::index');
$routes->post('upload', 'Upload::upload');

Step 5: Create Upload Directory

Run the following command to create a directory:

mkdir writable/uploads

Step 6: Testing

Run the following command to start the development server:

php spark serve

Open your browser and navigate to http://localhost:8080.

Leave a Comment