CodeIgniter 4 - Image Upload With Preview Tutorial

Apr 23, 2022 . Admin



Hi Guys,

Today our leading topic is codeigniter 4 photo upload with preview example. if you want to see example of file upload with preview in codeigniter then you are a right place. you will learn simple image upload with preview in codeigniter example. you will learn how to upload image with preview in codeigniter. So, let's follow few step to create example of codeigniter upload image with preview.

CodeIgniter 4 image upload with preview example tutorial. Here, you will learn how to upload images in Codeigniter 4 projects with preview using jquery.

Step 1: Install Codeigniter 4

This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
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.

app/config/app.php
public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table

in this section, we require to create a database name demo, so allow’s open your PHPMyAdmin and create the database with the call demo. After correctly create a database, you could use the under square question for creating a desk to 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.

app/Config/Database.php
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

In this step we need to create 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 :

app/Controllers/Form.php
<?php 
namespace App\Controllers;
use CodeIgniter\Controller;
 
class Form extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
         return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    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]',
            ],
        ]);
 
        $msg = 'Please select a valid file';
  
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');
 
        $data = [
 
            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()
        ];
 
            $save = $builder->insert($data);
            $msg = 'File has been uploaded';
        }
 
        return redirect()->to( base_url('public/index.php/form') )->with('msg', $msg);
 
    }
}
Step 6: Create Views

In this section we require to create form.php, go to application/views/ folder and create form.php file. and update the following HTML into your files:

application/views/form.php
<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter 4 Image upload with preview example - Mywebtuts.com</title>
    <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.js"></script> 
</head>
<body>
    <div class="container">
        <br>
     
        <?php if (session('msg')) : ?>
            <div class="alert alert-info alert-dismissible">
                <?= session('msg') ?>
                <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
            </div>
        <?php endif ?>
 
        <div class="row">
            <div class="col-md-9">
                <form action="<?php echo base_url('form/store');?>" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">
                    <div class="row">
                        <div class="form-group col-md-6">
                            <label for="formGroupExampleInput">Name</label>
                            <input type="file" name="file" class="form-control" id="file" onchange="readURL(this);" accept=".png, .jpg, .jpeg" />
                        </div>           
         
                        <div class="form-group col-md-6">
                            <img id="blah" src="https://www.tutsmake.com/wp-content/uploads/2019/01/no-image-tut.png" class="" width="200" height="150"/>
                        </div> 
                   
                        <div class="form-group">
                            <button type="submit" id="send_form" class="btn btn-success">Submit</button>
                        </div>
                    </div>                      
                </form>
            </div>
        </div>
    </div>
</div>
<script>

    /*------------------------------------------
    --------------------------------------------
    About 
    --------------------------------------------
    --------------------------------------------*/
    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]);
        }
    }
</script> 
</body>
</html>
Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/

It will help you....

#Codeigniter 4