Using this CodeIgniter 4 upload multiple images using drag and drop using dropzone tutorial you will learn how to drag and drop multiple image upload in codeigniter 4. This quick guide will help you step by step drag and drop multiple file upload with dropzone js and preview and store to database.
CodeIgniter upload multiple images using drag and drop using dropzone
Dropzone is a jQuery library, Through which we drag and drop the file and save it in our database. Its not a though but need to attention for the code, you just need to add dropzone js and css cdn in your laravel project. Dropzone.js also provide filter like we can make validation for max upload, specific image or file extension etc.
Uploading image or file with dropzone in Laravel is no more going to be a difficult task. I am going to share how does Laravel dropzone file upload functionality is made from scratch.
Begin implementing a seamless drag and drop image upload feature using Dropzone.js:
Step 1: Set Up CodeIgniter 4 App
Run the following command to install CodeIgniter 4 application:
composer create-project codeigniter4/appstarter codeigniter-drag-drop
Step 2: Create Database and Table
Create a database and table using the following SQL queries:
CREATE DATABASE `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 the .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 a model named ImageModel.php
file. Update the following code 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. Update the following code 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 the application server for testing:
php spark serve
Type URL: http://localhost:8080/image-upload in your browser to see the drag-and-drop multiple image upload form in CodeIgniter 4 projects.