Throughout this Codeigniter 4 Ajax File Upload Tutorial we will explain you how to integrate file upload in Codeigniter using ajax with validation and save data in database.
Step 1 – Setting up CodeIgniter 4
Begin by downloading CodeIgniter 4 from the official website. Extract the downloaded zip file into your xampp/htdocs
directory. Next, open the app/Config/App.php
file and set the base URL:
public $baseURL = 'http://localhost/your-project/public';
Step 2 – Creating the File Upload Form
Navigate to the app/Views
directory and create a new file named upload_form.php
. Add the following HTML code to create a basic form for file uploads:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX File Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>AJAX File Upload</h1>
<form id="upload-form" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit">Upload</button>
</form>
<div id="response"></div>
</body>
</html>
Step 3 – Adding AJAX to the Form
Include the following JavaScript code within upload_form.php
to handle the AJAX request and update the webpage dynamically:
<script>
$(document).ready(function () {
$('#upload-form').on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
$('#response').html('<p>' + response.message + '</p>');
} else {
$('#response').html('<p>' + response.errors.file + '</p>');
}
}
});
});
});
</script>
Step 4 – Creating the Controller
In the app/controllers
directory, create a new file named UploadController.php
. Implement the following methods to handle the file upload process:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class UploadController extends Controller
{
public function index()
{
return view('upload_form');
}
public function upload()
{
$validationRule = [
'file' => [
'label' => 'File',
'rules' => 'uploaded[file]|mime_in[file,image/jpg,image/jpeg,image/gif,image/png]|max_size[file,2048]',
],
];
if (! $this->validate($validationRule)) {
return $this->response->setJSON(['success' => false, 'errors' => $this->validator->getErrors()]);
}
$file = $this->request->getFile('file');
if ($file->isValid() && ! $file->hasMoved()) {
$newName = $file->getRandomName();
$file->move(WRITEPATH . 'uploads', $newName);
return $this->response->setJSON(['success' => true, 'message' => 'File uploaded successfully.']);
}
return $this->response->setJSON(['success' => false, 'message' => 'File upload failed.']);
}
}
Step 5 – Defining Routes
Update the app/Config/Routes.php
file to define the routes for handling AJAX file uploads:
$routes->get('/', 'UploadController::index');
$routes->post('upload', 'UploadController::upload');
Step 6 – Test the Application
To run the application, navigate to your project directory and start the server using the following command:
cd /your-project
php spark serve
Access the file upload feature in your web browser by entering http://localhost:8080/
.