Codeigniter 4 Image Upload Preview Example

CodeIgniter 4 image upload preview tutorial. In this example, i will show you on how to upload image file with preview and validation in Codeigniter 4 apps using jQuery library.

It is a basic and easy task for previewing any image before uploading into database and directory. For this in this tutorial, I will use jquery library and show preview before uploading the image.

Uploading images with preview is a basic requirement in any applications. If you are creating any form with image file upload field in codeigniter 4 app. And want to display preview of image before uploading into database and directory in codeigniter 4 apps. So, in this tutorial, you will learn how to show preview of image file before upload in codeigniter 4 apps.

For the CodeIgniter 4 image upload preview example , I’ll create a simple image upload form with preview. And store image into database and codeigniter 4 apps directory.

How to Upload Image With Preview In Codeigniter 4 Apps

You can learn by following the steps given below on codeIgniter 4 image upload preview:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to 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.

Set Base URL like this

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

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE TABLE images (
    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

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,
	];

Step 5 – Create Controller

Create FormController.php file. So, visit app/Controllers directory and create FormController.php.Then add the following code into it:

<?php namespace App\Controllers;

use CodeIgniter\Controller;

class FormController extends Controller
{
    public function index()
    {    
         return view('image_form');
    }

   public function store()
   {  

	 helper(['form', 'url']);
        
	 $db      = \Config\Database::connect();
         $builder = $db->table('images');

        $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 image file';
 
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');

          $data = [

            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()
          ];

          $save = $builder->insert($data);
          $msg = 'Image has been uploaded';
        }

       return redirect()->to( base_url('/') )->with('msg', $msg);

	}
}

The index() function renders the contact form template into the view.

The store() method handles the form of validation and contains various variables. And store image into db and directory.

Step 6 – Create Views

Create image_form.php view file, so visit application/views/ directory and create image_form.php file. Then add the following HTML into image_form.php file:

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Image upload with preview example</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('FormController/store');?>" name="image_upload_preview" id="image_upload_preview" method="post" accept-charset="utf-8" enctype="multipart/form-data">
         <div class="row">
          <div class="form-group col-md-6">
            <label for="formGroupExampleInput">Please Select Image</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="http://laratutorials.com/wp-content/uploads/2021/07/Codeigniter-4-Image-Upload-Validation-Example.jpg" class="" width="200" height="150"/>
          </div> 
          
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
         
        </form>
       </div>
      </div>

    </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]);
    }
 }
</script> 
</body>
</html>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

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

Note that, the routes will be displaying the image upload form and submitting the data in the database on successful form submission.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

CodeIgniter 4 image upload preview with validation example tutorial. In this example,you have learned how to upload image with preview and validation in Codeigniter 4 apps. And also will learned how to store image into db and directory..

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *