How To File Upload With Progress Bar In PHP

Websolutionstuff | Sep-21-2022 | Categories : Laravel PHP jQuery

In this article, we will see how to file upload with a progress bar in PHP using ajax jquery. The file upload feature is the most used functionality for the dynamic web application. Generally, the page is refreshed when you upload a file in PHP. To make this file upload, using jQuery and Ajax can upload files/images without page refresh. While the file is uploading to the server, the web page stays in the loading state. It’s very difficult to track the upload progress.

Generally, a progress bar is utilized to show progress representation in percentage format for upload, download, or installation. In this tutorial, we will show you how to upload files in PHP and make a progress bar utilizing jQuery and Ajax.

So, let's see how to file upload with the progress bar using jquery.

In the example, we will create a script for an ajax progress bar with a percentage.

  • HTML form to select file.
  • Display the progress bar when the upload is in the process using jquery.
  • Add upload completion percentage to the progress bar in real-time using Ajax.
  • Upload file to server using PHP.

Before getting started to integrate file upload with the progress bar, take a look at the file structure.

php_file_upload_with_progress_bar_jquery/
├── index.html
├── upload.php
├── uploads/
├── js/
│   └── jquery.min.js
├── css/
│   └── style.css
└── images/

 

 

File Upload Form with Progress Bar

The index.html file handles the file selection and lives upload progress display operations.

File Upload Form


1. Create an HTML form with a file input field and a submit button.

  • The <form> tag must contain the enctype="multipart/form-data" attributes.
  • The <input> tag must contain type="file".
<!-- File upload form -->
<form id="uploadForm" enctype="multipart/form-data">
    <label>Choose File:</label>
    <input type="file" name="file" id="fileInput">
    <input type="submit" name="submit" value="UPLOAD"/>
</form>

2. Define an HTML element to display the progress bar.

<!-- Progress bar -->
<div class="progress">
    <div class="progress-bar"></div>
</div>

3. Define an HTML element to display the file upload status.

<!-- Display upload status -->
<div id="uploadStatus"></div>

 

Ajax File Upload with Progress Bar

The jQuery and Ajax are used to upload files with a progress bar, so include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The following jQuery code sends the selected file data to the server-side script without reloading the page via Ajax.

  • On form submission, the selected file data is sent to the server-side script (upload.php) using jQuery and Ajax.
    • The xhr option of the $.ajax() method is used to track the upload progress.
    • The window.XMLHttpRequest() method creates a new XMLHttpRequest object.
    • The progress event of XMLHttpRequest upload property indicates the amount of progress made so far.
    • The upload progress percentage is attached to the progress bar.
  • The FormData object is used to retrieve the submitted file data.
    • Based on the response, the upload status is displayed on the webpage.
  • On the change event, the file type is validated based on the allowed types.
    • The File API is used to get the type of the selected file.
    • The MIME type of the selected file is validated and restricts the user to upload only the image (.jpeg/.jpg/.png/.gif) or PDF (.pdf) or MS Word (.doc/.docx) file.
    • The includes() the method determines whether allowedTypes array contains the selected file type
<script>
$(document).ready(function(){
    // File upload via Ajax
    $("#uploadForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = ((evt.loaded / evt.total) * 100);
                        $(".progress-bar").width(percentComplete + '%');
                        $(".progress-bar").html(percentComplete+'%');
                    }
                }, false);
                return xhr;
            },
            type: 'POST',
            url: 'upload.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $(".progress-bar").width('0%');
                $('#uploadStatus').html('<img src="images/loading.gif"/>');
            },
            error:function(){
                $('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
            },
            success: function(resp){
                if(resp == 'ok'){
                    $('#uploadForm')[0].reset();
                    $('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
                }else if(resp == 'err'){
                    $('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
                }
            }
        });
    });
	
    // File type validation
    $("#fileInput").change(function(){
        var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
        var file = this.files[0];
        var fileType = file.type;
        if(!allowedTypes.includes(fileType)){
            alert('Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF).');
            $("#fileInput").val('');
            return false;
        }
    });
});
</script>

 

 

Upload File to Server using PHP

The upload.php the file is called by the Ajax request to handle the file upload process with PHP.

  • Retrieve the file information from posted data using the PHP $_FILES method.
  • Upload the file to the server using move_uploaded_file() function in PHP.
  • Render file upload status that returns to the Ajax success function.
<?php 
$upload = 'err'; 
if(!empty($_FILES['file'])){ 
     
    // File upload configuration 
    $targetDir = "uploads/"; 
    $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg', 'gif'); 
     
    $fileName = basename($_FILES['file']['name']); 
    $targetFilePath = $targetDir.$fileName; 
     
    // Check whether file type is valid 
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
    if(in_array($fileType, $allowTypes)){ 
        // Upload file to the server 
        if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)){ 
            $upload = 'ok'; 
        } 
    } 
} 
echo $upload; 
?>

 


You might also like:

Recommended Post
Featured Post
How To Install React In Laravel 9
How To Install React In Larave...

In this article, we will see how to install React in laravel 9. We will also install react with laravel 9 and...

Read More

Aug-15-2022

How To Restrict User Access From IP Address In Laravel 9
How To Restrict User Access Fr...

Imagine this: You've made a super cool website, and now you want to make sure only the right people can use it. That...

Read More

Jan-03-2023

Laravel 9 Inner Join Query Example
Laravel 9 Inner Join Query Exa...

In this article, we will see laravel 9 inner join query example. Also, see how to join two tables in laravel 9. In larav...

Read More

Mar-30-2022

Laravel 11 Socialite Login with Gitlab Account
Laravel 11 Socialite Login wit...

Hello, Laravel web developers! In this article, I'll show you how to log in with GitLab in Laravel 11 using Socialit...

Read More

Aug-14-2024