Codeigniter 4 Multiple Image Upload with Preview

CodeIgniter 4 multiple image upload with preview tutorial. In this example, i will guide you on how to upload multiple images with preview in Codeigniter 4 apps.

If you want to upload multiple images simultaneously and also want to show preview of images. Before storing those images in the database. So, In this codeigniter multiple image upload with preview example; you will learn how to display preview of multiple images in database and directory in codeigniter 4 app.

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

Upload Multiple Image with Preview in Codeigniter 4

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Table in Database
  • 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 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 Table in Database

Create a 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 UploadMultiplePreview.php file. So, visit app/Controllers directory and create UploadMultiplePreview.php.Then add the following code into it:

<?php 
namespace App\Controllers;
use CodeIgniter\Controller;

class UploadMultiplePreview extends Controller
{

    public function index() {
        return view('upload_multiple_image_preview');
    }

    function uploadFiles() {
        helper(['form', 'url']);
 
        $database = \Config\Database::connect();
        $db = $database->table('users');
 
        $msg = 'Please select a valid files';
  
        if ($this->request->getFileMultiple('images')) {
 
             foreach($this->request->getFileMultiple('images') as $file)
             {   
 
                $file->move(WRITEPATH . 'uploads');
 
              $data = [
                'name' =>  $file->getClientName(),
                'type'  => $file->getClientMimeType()
              ];
 
              $save = $db->insert($data);
              $msg = 'Files have been successfully uploaded';
             }
        }
 
        return redirect()->to( base_url('/') )->with('msg', $msg);        
    }

}
  • index() – It renders the multiple images uploading form with preview in Codeigniter 4 view.
  • uploadFiles() – This functions helps in uploading the multiple images in database and directory.

Step 6 – Create Views

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

<!DOCTYPE html>
<html>

<head>
  <title>Upload Multiple Images with Preview in Codeigniter 4 - LaraTutorials.com</title>
</head>


<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

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

<style type="text/css">
.thumb {
  margin: 24px 5px 20px 0;
  width: 150px;
  float: left;
}

#blah {
  border: 2px solid;
  display: block;
  background-color: white;
  border-radius: 5px;
}
</style>

<body>
  <div class="container">
    <div id="divMsg" class="alert alert-success" style="display: none"> <span id="msg"></span> </div>
    <br>
    <br>
    <div class="row" id="blah">
      <form method="post" id="" action="<?php echo base_url('UploadMultiplePreview/uploadFiles');?>" enctype="multipart/form-data">
        <div class="form-control col-md-12">
          <input type="file" id="image_file" multiple="multiple" />
          <br>
          <div id="uploadPreview"></div>
        </div>
        </br>
        </br>
        <br>
        <div class="form-group col-md-6">
          <button>Submit</button>
        </div>
      </form>
    </div>
  </div>
</body>
<script type="text/javascript">

// var url = window.URL || window.webkitURL; // alternate use
function readImage(file) {
  var reader = new FileReader();
  var image = new Image();
  reader.readAsDataURL(file);
  reader.onload = function(_file) {
    image.src = _file.target.result; // url.createObjectURL(file);
    image.onload = function() {
      var w = this.width,
        h = this.height,
        t = file.type, // ext only: // file.type.split('/')[1],
        n = file.name,
        s = ~~(file.size / 1024) + 'KB';
      $('#uploadPreview').append('<img src="' + this.src + '" class="thumb">');
    };
    image.onerror = function() {
      alert('Invalid file type: ' + file.type);
    };
  };
}
$("#image_file").change(function(e) {
  if(this.disabled) {
    return alert('File upload not supported!');
  }
  var F = this.files;
  if(F && F[0]) {
    for(var i = 0; i < F.length; i++) {
      readImage(F[i]);
    }
  }
});
</script>
</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('UploadMultiplePreview');
$routes->get('/', 'UploadMultiplePreview::index');

Note that, the routes will be displaying the multiple image upload preview 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 multiple image preview example tutorial. In this example, you have learned how to upload multiple images with preview in Codeigniter 4 apps. And also will learned how to store multiple 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
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4

Be First to Comment

Leave a Reply

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