Codeigniter 4 Ajax Image Upload with Preview Example

Codeigniter

Nicesnippets

1185

05-08-2020


Codeigniter 4 Ajax Image Upload with Preview Example

Hi Guys,

In this example,I will learn you how to use ajax image upload with preview in codeigniter 4.you can easy and simply use ajax image upload with preview in codeigniter 4.

CodeIgniter 4 tutorial upload the image file using jquery ajax. Here, you will learn how to upload the image using jQuery ajax in Codeigniter 4 projects with preview.

So, let's follow few bellow step to ajax image upload with preview example:

Step 1: Download Fresh Codeigniter 4

In First step we will download fresh version of Codeigniter 4, so if you haven't download yet then download from here : Download Codeigniter 4.

Step 2: Basic Configurations

Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

public $baseURL = 'http://localhost:8080';

To

public $baseURL = 'http://localhost/demo/';

Step 3: Create Database With Table

In this step, we need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

CREATE TABLE files (

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

name varchar(100) NOT NULL COMMENT 'Name',

type varchar(255) NOT NULL COMMENT 'file type',

created_at varchar(20) NOT NULL COMMENT 'Created date',

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;

Step 4: Setup Database Credentials

In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.

public $default = [

'DSN' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'demo',

'DBDriver' => 'MySQLi',

'DBPrefix' => '',

'pConnect' => false,

'DBDebug' => (ENVIRONMENT !== 'production'),

'cacheOn' => false,

'cacheDir' => '',

'charset' => 'utf8',

'DBCollat' => 'utf8_general_ci',

'swapPre' => '',

'encrypt' => false,

'compress' => false,

'strictOn' => false,

'failover' => [],

'port' => 3306,

];

Step 5: Create Controller

Now Go to app/Controllers and create a controller name Form.php. In this controller, we will create some method/function. We will build some of the methods like :

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Form extends Controller

{

public function index()

{

return view('form');

}

public function store()

{

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

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

$builder = $db->table('file');

$validated = $this->validate([

'file' => [

'uploaded[file]',

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

'max_size[file,4096]',

],

]);

$response = [

'success' => false,

'data' => '',

'msg' => "Image has not been uploaded successfully"

];

if ($validated) {

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

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

$data = [

'name' => $avatar->getClientName(),

'type' => $avatar->getClientMimeType()

];

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

$response = [

'success' => true,

'data' => $save,

'msg' => "Image has been uploaded successfully"

];

}

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

}

}

Step 6: Create Views

Now we need to create form.php, go to application/views/ folder and create form.php file. and update the following HTML into your files:

<!DOCTYPE html>

<html>

<head>

<title>Codeigniter 4 Ajax Image upload with preview Example</title>

</head>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<style type="text/css">

#blah {

width: 600px;

height: 300px;

border: 2px solid;

display: block;

margin: 10px;

background-color: white;

border-radius: 5px;

box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);

transition: all 0.3s cubic-bezier(.25,.8,.25,1);

overflow: hidden;

}

</style>

<body>

<div class="container">

<div class="row">

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

<div class="col-md-7">

<h1> codeigniter 4 tutorial upload image file using jquery ajax </h1></br>

<div id="divMsg" class="alert alert-success" style="display: none">

<span id="msg"></span>

</div>

<img id="blah" src="//www.tutsmake.com/ajax-image-upload-with-preview-in-codeigniter/" alt="your image" /></br></br>

<input type="file" name="file" multiple="true" accept="image/*" id="finput" onchange="readURL(this);"></br></br>

<button class="btn btn-success">Submit</button>

</div>

<div class="col-md-5"></div>

</form>

</div>

</div>

<script>

function readURL(input, id) {

id = id || '#blah';

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

var reader = new FileReader();

reader.onload = function (e) {

$(id)

.attr('src', e.target.result)

.width(200)

.height(150);

};

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

}

}

$(document).ready(function(){

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

$('.btn-success').html('sending');

$('.btn-success').prop('disabled');

e.preventDefault();

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

{

alert("Please Select the File");

$('.btn-success').html('submit');

$('.btn-success').prop('enabled');

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

}

else

{

$.ajax({

url:"<?php echo base_url(); ?>form/store",

method:"POST",

data:new FormData(this),

contentType: false,

cache: false,

processData:false,

dataType: "json",

success:function(res)

{

console.log(res.success);

if(res.success == true){

$('#blah').attr('src','//www.tutsmake.com/ajax-image-upload-with-preview-in-codeigniter/');

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

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

}

else if(res.success == false){

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

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

}

setTimeout(function(){

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

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

}, 3000);

$('.btn-success').html('submit');

$('.btn-success').prop('enabled');

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

}

});

}

});

});

</script>

</body>

</html>

This below line display error messages on your web page:

<div id="divMsg" class="alert alert-success" style="display: none">

<span id="msg"></span>

</div>

This below javascript code show preview of your image before upload to server in codeigniter 4 projects:

function readURL(input, id) {

id = id || '#blah';

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

var reader = new FileReader();

reader.onload = function (e) {

$(id)

.attr('src', e.target.result)

.width(200)

.height(150);

};

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

}

}

The below given ajax code is used to upload image into the server in codeigniter 4 projects. So include this code into your web page:

$(document).ready(function(){

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

$('.btn-success').html('sending');

$('.btn-success').prop('disabled');

e.preventDefault();

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

{

alert("Please Select the File");

$('.btn-success').html('submit');

$('.btn-success').prop('enabled');

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

}

else

{

$.ajax({

url:"public/index.php/form/store",

method:"POST",

data:new FormData(this),

contentType: false,

cache: false,

processData:false,

dataType: "json",

success:function(res)

{

console.log(res.success);

if(res.success == true){

$('#blah').attr('src','//www.tutsmake.com/ajax-image-upload-with-preview-in-codeigniter/');

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

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

}

else if(res.success == false){

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

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

}

setTimeout(function(){

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

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

}, 3000);

$('.btn-success').html('submit');

$('.btn-success').prop('enabled');

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

}

});

}

});

});

Step 7: Start Development server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/form

It will help you...


Recommended Posts