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 Drag and Drop Multiple Image Upload Tutorial

Last Updated on July 19, 2024 by

Dropzone JS library helps developers to implement drag and drop image file upload with add and remove button feature in CodeIgniter 4 applications.

Let’s start creating a drag and drop image upload using dropzone.js:

Step 1: Set Up CodeIgniter 4 Project

Run the following command to install codeIgniter 4 application:

composer create-project codeigniter4/appstarter codeigniter4-drag-drop

Step 2: Create Database and Table

Create database and table by using the following sql queries:

CREATE DATABASES `test`;

CREATE TABLE `images` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `file_name` varchar(255) NOT NULL,
    `uploaded_on` datetime NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 3: Configure Database

Edit .env file and update it with your database credentials:

database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi

Step 4: Create Model

Go to app/models directory and create model named ImageModel.php file, and update the following code in it to handle image data:

// File: app/Models/ImageModel.php
namespace App\Models;

use CodeIgniter\Model;

class ImageModel extends Model
{
    protected $table = 'images';
    protected $primaryKey = 'id';
    protected $allowedFields = ['file_name', 'uploaded_on'];
}

Step 5: Create Controller

Create a controller file named ImageUpload.php in app/controllers directory, and update the following code in it to handle the upload process:

// File: app/Controllers/ImageUpload.php
namespace App\Controllers;

use App\Models\ImageModel;
use CodeIgniter\Controller;

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

    public function upload()
    {
        $imageModel = new ImageModel();

        $validationRule = [
            'file' => [
                'label' => 'Image File',
                'rules' => 'uploaded[file]|is_image[file]|max_size[file,1024]',
            ],
        ];

        if (!$this->validate($validationRule)) {
            return $this->response->setJSON(['status' => 'error', 'errors' => $this->validator->getErrors()]);
        }

        $files = $this->request->getFiles();

        if ($files) {
            foreach ($files['file'] as $file) {
                if ($file->isValid() && !$file->hasMoved()) {
                    $fileName = $file->getRandomName();
                    $file->move('uploads/', $fileName);

                    $imageModel->save([
                        'file_name' => $fileName,
                        'uploaded_on' => date('Y-m-d H:i:s')
                    ]);
                }
            }
            return $this->response->setJSON(['status' => 'success']);
        }
        return $this->response->setJSON(['status' => 'error']);
    }
}

Step 6: Create Upload Form View

Create a view file named upload_form.php for the drag-and-drop upload images using Dropzone.js CDN:

<!-- File: app/Views/upload_form.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag and Drop Multiple Image Upload CodeIgniter 4 - ItcodStuff.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.css">
    <style>
        .dropzone {
            border: 2px dashed #007bff;
            border-radius: 5px;
            background: #f9f9f9;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <h4 class="mb-4">Drag and Drop Multiple Image Upload</h4>
                <form action="<?= base_url('image-upload/upload') ?>" class="dropzone" id="myDropzone">
                    <div class="dz-message">
                        <h3>Drop files here or click to upload.</h3>
                    </div>
                </form>
                <div id="status" class="mt-3"></div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>
    <script>
        Dropzone.options.myDropzone = {
            paramName: 'file',
            maxFilesize: 1, // MB
            acceptedFiles: 'image/*',
            init: function() {
                this.on("success", function(file, response) {
                    document.getElementById('status').innerHTML = '<div class="alert alert-success">Images uploaded successfully!</div>';
                });
                this.on("error", function(file, response) {
                    document.getElementById('status').innerHTML = '<div class="alert alert-danger">Failed to upload images!</div>';
                });
            }
        };
    </script>
</body>
</html>

Step 7: Update Routes

Edit the app/Config/Routes.php file to include the routes for the image upload functionality:

// File: app/Config/Routes.php
$routes->get('image-upload', 'ImageUpload::index');
$routes->post('image-upload/upload', 'ImageUpload::upload');

Step 8: Test the Application

Run the following command to start application server for testing:

php spark serve

Type url: http://localhost:8080/image-upload on browser to see the drag-and-drop multiple image upload form in codeIgniter 4 projects.

Leave a Comment