File Upload with Progress Bar using CodeIgniter and Ajax
File uploading is a common feature of dynamic web applications. Learn here to file upload using Ajax without page refresh. In this tutorial, we will learn how to File Upload with Progress Bar using CodeIgniter, jQuery, and Ajax. This is a very simple example, you can just copy-paste, and change it according to your requirements.
Before started to implement the File Upload with Progress Bar using CodeIgniter, look files structure:
- file-upload-with-progress-bar-using-codeigniter-jquery-ajax
- application
- config
- autoload.php
- constants.php
- routes.php
- controllers
- Upload.php
- views
- upload
- index.php
- templates
- header.php
- footer.php
- upload
- config
- system
- index.php
- assets
- css
- style.css
- uploads
- application
Step 1: Create an HTML form
a- File Upload Form
1 2 3 4 5 6 7 8 9 10 11 12 |
<form id="upload-form" class="upload-form" method="post"> <div class="row align-items-center"> <div class="form-group col-md-9"> <label for="inputEmail4">Choose a file:</label> <input type="file" class="form-control" id="upl-file" name="upl_file"> <span id="chk-error"></span> </div> <div class="col"> <button type="submit" class="btn btn-primary mt-3 float-left" id="upload-file"><i class="fa fa-upload" aria-hidden="true"></i> Upload</button> </div> </div> </form> |
b- HTML element to display the progress bar
1 2 3 4 5 6 7 |
<div class="row align-items-center"> <div class="col"> <div class="progress"> <div id="file-progress-bar" class="progress-bar"></div> </div> </div> </div> |
c- HTML element to display the file uploaded status
1 2 3 4 5 |
<div class="row align-items-center"> <div class="col"> <div id="uploaded_file"></div> </div> </div> |
Step 2: Include the jQuery library
The jQuery and Ajax is used to upload file with a progress bar, so include the jQuery library.
1 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> |
Ajax Code Uploding file with reloding page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
jQuery(document).on('submit', '#upload-form', function(e){ jQuery("#chk-error").html(''); e.preventDefault(); $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(element) { if (element.lengthComputable) { var percentComplete = ((element.loaded / element.total) * 100); $("#file-progress-bar").width(percentComplete + '%'); $("#file-progress-bar").html(percentComplete+'%'); } }, false); return xhr; }, type: 'POST', url: 'upload.php', data: new FormData(this), contentType: false, cache: false, processData:false, dataType:'json', beforeSend: function(){ $("#file-progress-bar").width('0%'); }, success: function(json){ if(json == 'success'){ $('#upload-form')[0].reset(); $('#uploaded_file').html('<p style="color:#28A74B;">File has uploaded successfully!</p>'); }else if(json == 'failed'){ $('#uploaded_file').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); // Check File type validation $("#upl-file").change(function(){ var allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']; var file = this.files[0]; var fileType = file.type; if(!allowedTypes.includes(fileType)) { jQuery("#chk-error").html('<small class="text-danger">Please choose a valid file (JPEG/JPG/PNG/GIF/PDF/DOC/DOCX)</small>'); $("#upl-file").val(''); return false; } else { jQuery("#chk-error").html(''); } }); |
Step 3: Create a view
Create a view file named index.php inside “application/views/upload” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<?php include('templates/header.php');?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Ajax File Upload with Progress Bar using PHP and jQuery</h2> </div> <form id="upload-form" class="upload-form" method="post"> <div class="row align-items-center"> <div class="form-group col-md-9"> <label for="inputEmail4">Choose a file:</label> <input type="file" class="form-control" id="upl-file" name="upl_file"> <span id="chk-error"></span> </div> <div class="col"> <button type="submit" class="btn btn-primary mt-3 float-left" id="upload-file"><i class="fa fa-upload" aria-hidden="true"></i> Upload</button> </div> </div> </form> <hr> <div class="row align-items-center"> <div class="col"> <div class="progress"> <div id="file-progress-bar" class="progress-bar"></div> </div> </div> </div> <div class="row align-items-center"> <div class="col"> <div id="uploaded_file"></div> </div> </div> </div> </section> <?php include('templates/footer.php');?> <script type="text/javascript"> jQuery(document).on('submit', '#upload-form', function(e){ jQuery("#chk-error").html(''); e.preventDefault(); $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(element) { if (element.lengthComputable) { var percentComplete = ((element.loaded / element.total) * 100); $("#file-progress-bar").width(percentComplete + '%'); $("#file-progress-bar").html(percentComplete+'%'); } }, false); return xhr; }, type: 'POST', url: 'upload.php', data: new FormData(this), contentType: false, cache: false, processData:false, dataType:'json', beforeSend: function(){ $("#file-progress-bar").width('0%'); }, success: function(json){ if(json == 'success'){ $('#upload-form')[0].reset(); $('#uploaded_file').html('<p style="color:#28A74B;">File has uploaded successfully!</p>'); }else if(json == 'failed'){ $('#uploaded_file').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); // Check File type validation $("#upl-file").change(function(){ var allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']; var file = this.files[0]; var fileType = file.type; if(!allowedTypes.includes(fileType)) { jQuery("#chk-error").html('<small class="text-danger">Please choose a valid file (JPEG/JPG/PNG/GIF/PDF/DOC/DOCX)</small>'); $("#upl-file").val(''); return false; } else { jQuery("#chk-error").html(''); } }); </script> |
Step 4: Create a controller file
Create a controller file named Upload.php inside “application/controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Version: 1.0.0 * * Description of Upload Controller * * @author TechArise Team * * @email info@techarise.com * **/ // Upload class class Upload extends CI_Controller { //Load libraries in Constructor. public function __construct() { parent::__construct(); } // index method public function index() { $data['metaDescription'] = 'File Upload with Progress Bar using CodeIgniter, jQuery and Ajax'; $data['metaKeywords'] = 'File Upload with Progress Bar using CodeIgniter, jQuery and Ajax'; $data['title'] = "File Upload with Progress Bar using CodeIgniter, jQuery and Ajax | TechArise"; $data['breadcrumbs'] = array('File Upload with Progress Bar using CodeIgniter, jQuery and Ajax ' => '#'); $this->load->view('upload/index', $data); } // Upload file/image method public function upl() { $this->load->library('pagination'); $json = array(); $path = ROOT_UPL_IMAGE; // Define file rules $initialize = $this->upload->initialize(array( "upload_path" => $path, "allowed_types" => "gif|jpg|jpeg|png|bmp|pdf|doc|docx", "remove_spaces" => TRUE )); if (!$this->upload->do_upload('upl_file')) { $error = array('error' => $this->upload->display_errors()); echo $this->upload->display_errors(); $json = 'failed'; } else { $data = $this->upload->data(); $imagename = $data['file_name']; $json = 'success'; } header('Content-Type: application/json'); echo json_encode($json); } } ?> |
Step 5:Create a view(header)
Create a view file named header.php inside “application/views/templates” folder.
This view contains the header section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header section.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title><?php print $title; ?></title> <link rel="icon" type="image/ico" href="<?php print HTTP_IMAGE_PATH; ?>favicon.ico"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="<?php print HTTP_CSS_PATH; ?>style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
Step 6: Create a view(footer)
Create a view file named footer.php inside “application/views/templates” folder.
This view contains the footer section of the webpage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </body> </html> |