Codeigniter 4 Ajax Image Upload With Preview Example Tutorial

Codeigniter 4 , Codeigniter

Nicesnippets

455

06-09-2021


Codeigniter 4 Ajax Image Upload With Preview Example Tutorial

Hi guys,

Today i will explained Codeigniter 4 Ajax Image Upload With Preview Example Tutorial. This example is so easy to use in Codeigniter 4.

But do you know how to create this common feature of uploading an image and display the image preview in the Codeigniter 4 application using the jQuery AJAX (Asynchronous JavaScript and XML)?

In this Codeigniter ajax image upload with preview tutorial, we will explain how to step by step create image upload and preview functionality in Codeigniter with the help of jQuery ajax from scratch.

This example to i am explained in seven steps.So let's start to the example.

Step 1 : Install Codeigniter App


Codeigniter Project Project install in a two ways.

<?php

https://codeigniter.com/download

or

composer create-project codeigniter4/appstarter project_name

?>

Step 2 : Enable Error Debugging

You need to get to the app/Config/Boot/development.php and app/Config/Boot/production.php file and change the display_errors property to 1 from 0.

ini_set('display_errors', '1');

Step 3 : Create Database And Table

In this section, we need to understand how to create a new table for file upload using the SQL query. We assume you have already created the database. Run the following command in the SQL tab of PHPMyAdmin to create a new table into the database.

CREATE TABLE users (

id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',

img_name varchar(100) NOT NULL COMMENT 'Image Name',

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='user table' AUTO_INCREMENT=1;

Step 4 : Add Database Details

In the app/Config/Database.php file, look for $default public variable, and there you need to add the database name, user name and password.

public $default = [

'DSN' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'codeigniter_db',

'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,

];

CodeIgniter\Database\Exceptions\DatabaseException

There are a high chance that you might get Unable to connect database : Codeigniter the error, especially if you are working with MAMP or XAMP servers. You can define either of the hostname for MAMP or XAMP.

# XAMP

public $default = [

'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

]

# MAMP

public $default = [

'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

]

Step 5 : Create AJAX Image Upload Controller

In the next step, you have to create a new controller file inside the app/Controllers folder; there, after open the app/Controllers/AjaxFileUpload.php file and update the given below code.

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class AjaxFileUpload extends Controller

{

public function index()

{

return view('index');

}

public function upload()

{

helper(['form', 'url']);

$database = \Config\Database::connect();

$builder = $database->table('users');

$validateImage = $this->validate([

'file' => [

'uploaded[file]',

'mime_in[file, image/png, image/jpg,image/jpeg, image/gif]',

'max_size[file, 4096]',

],

]);

$response = [

'success' => false,

'data' => '',

'msg' => "Image could not upload"

];

if ($validateImage) {

$imageFile = $this->request->getFile('file');

$imageFile->move(WRITEPATH . 'uploads');

$data = [

'img_name' => $imageFile->getClientName(),

'file' => $imageFile->getClientMimeType()

];

$save = $builder->insert($data);

$response = [

'success' => true,

'data' => $save,

'msg' => "Image successfully uploaded"

];

}

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

}

}

Step 6 : Create Route

Furthermore, open the app/Config/Routes.php file and define the route that will allow you to open the CI app on the browser.

$routes->get('/', 'AjaxFileUpload::index');

Step 7 : Set Up File Upload View

Next, head over to app/Views/ folder inside here create the index.php file and update the following code inside the app/Views/index.php file.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Codeigniter 4 Ajax Image Upload With Preview Example Tutorial - Nicesnippets.com</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<style>

.container {

max-width: 750px

}

</style>

</head>

<body>

<div class="container mt-5">

<form method="post" id="upload_image_form" enctype="multipart/form-data">

<div id="alertMessage" class="alert alert-warning mb-3" style="display: none">

<span id="alertMsg"></span>

</div>

<div class="d-grid text-center">

<img class="mb-3" id="ajaxImgUpload" alt="Preview Image" src="https://via.placeholder.com/300" />

</div>

<div class="mb-3">

<input type="file" name="file" multiple="true" id="finput" onchange="onFileUpload(this);"

class="form-control form-control-lg" accept="image/*">

</div>

<div class="d-grid">

<button type="submit" class="btn btn-danger uploadBtn">Upload</button>

</div>

</form>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

function onFileUpload(input, id) {

id = id || '#ajaxImgUpload';

if (input.files && input.files[0]) {

var reader = new FileReader();

reader.onload = function (e) {

$(id).attr('src', e.target.result).width(300)

};

reader.readAsDataURL(input.files[0]);

}

}

$(document).ready(function () {

$('#upload_image_form').on('submit', function (e) {

$('.uploadBtn').html('Uploading ...');

$('.uploadBtn').prop('Disabled');

e.preventDefault();

if ($('#file').val() == '') {

alert("Choose File");

$('.uploadBtn').html('Upload');

$('.uploadBtn').prop('enabled');

document.getElementById("upload_image_form").reset();

} else {

$.ajax({

url: "<?php echo base_url(); ?>/AjaxFileUpload/upload",

method: "POST",

data: new FormData(this),

processData: false,

contentType: false,

cache: false,

dataType: "json",

success: function (res) {

console.log(res.success);

if (res.success == true) {

$('#ajaxImgUpload').attr('src', 'https://via.placeholder.com/300');

$('#alertMsg').html(res.msg);

$('#alertMessage').show();

} else if (res.success == false) {

$('#alertMsg').html(res.msg);

$('#alertMessage').show();

}

setTimeout(function () {

$('#alertMsg').html('');

$('#alertMessage').hide();

}, 4000);

$('.uploadBtn').html('Upload');

$('.uploadBtn').prop('Enabled');

document.getElementById("upload_image_form").reset();

}

});

}

});

});

</script>

</body>

</html>

Step 8 : Run Codeigniter Project

In the final segment of this guide, we have to start the CI development server, and this can be done by executing the below command.

php spark serve

Then next run the url in your browser.

http://localhost:8080

Output


Recommended Posts