File Upload with Progress Bar using PHP, jQuery and Ajax
File uploading is the most important feature of dynamic web application. User upload file/image to server then at that time page will not be refresh and after completing file/image upload it will display image on the web page without page refresh.In this tutorial, we will show you the simplest way to upload file/image with Progress Bar using PHP, jQuery and Ajax. This is a very simple example, you can just copy paste and change according to your requirement.
Before started to implement the File Upload with Progress Bar using PHP, look files structure:
- file-upload-with-progress-bar-using-php-jquery-ajax
- css
- uploads
- templates
- index.php
- upload.php
Step 1: Create an HTML form
i- 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> |
ii- 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> |
iii- 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 an HTML file named(index.php)
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 93 |
<?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: PHP Upload Image Handler (upload.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $json = array(); if(!empty($_FILES['upl_file'])){ $dir = "./uploads/"; $allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx'); $fileName = basename($_FILES['upl_file']['name']); $filePath = $dir.$fileName; // Check whether file type is valid $fileType = pathinfo($filePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to the server if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath)){ $json = 'success'; } else { $json = 'failed'; } } } header('Content-Type: application/json'); echo json_encode($json); ?> |
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
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 |
<!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>Integrate CCAvenue Payment Gateway using PHP | Tech Arise</title> <link rel="icon" type="image/ico" href="https://techarise.com/wp-content/themes/v1/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="css/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> |
footer.php
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> |