Sarnath India
  • Home
  • NodeJs
  • PHP
  • CSS
  • Javascript
  • Privacy Policy
  • Terms and Conditions
  • Disclaimer
  • DMCA
  • About Us

Subscribe to Updates

Get the latest creative news from FooBar about art, design and business.

What's Hot

How to Install Node.Js on Windows Machine

March 23, 2023

Image/File Upload with Progressbar Using PHP & Jquery

March 1, 2023

Display location on google map from address using javascript google map api

March 1, 2023
Facebook Twitter Instagram
Sarnath India
  • Home
  • NodeJs
  • PHP
  • CSS
  • Javascript
Sarnath India
Home»Javascript»Image/File Upload with Progressbar Using PHP & Jquery
Javascript

Image/File Upload with Progressbar Using PHP & Jquery

sarnathindiaBy sarnathindiaMarch 1, 20234 Mins Read
Facebook Twitter Pinterest LinkedIn WhatsApp Reddit Tumblr Email
Progressbar
Share
Facebook Twitter LinkedIn Pinterest Email

Uploading files or images is a common task in web development. In this tutorial, we will learn how to upload files or images using PHP and jQuery with the progress bar. Uploading files with progress bar helps users to track the progress of the upload process and also gives them an idea of how much time is left for the upload to complete.

Prerequisites

Before we start, make sure you have the following:

  • PHP installed on your system
  • A web server like Apache or Nginx
  • Basic knowledge of HTML, CSS, and JavaScript
  • jQuery library installed on your system

Image/File Upload with Progressbar Using PHP & Jquery

Step 1: Create HTML Form

The first step is to create an HTML form that allows users to upload files. Create a new file called “index.php” and add the following code:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Image/File Upload with Progressbar Using PHP & Jquery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="js/upload.js"></script>
    <style>
        #progress {
            width: 0%;
            height: 30px;
            background-color: #4CAF50;
            color: white;
            text-align: center;
            line-height: 30px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="fileToUpload" id="fileToUpload">
        <br>
        <input type="submit" value="Upload File" name="submit">
    </form>
    <div id="progress"></div>
</body>
</html>
HTML

Step 2: Create PHP Upload Script

Now, we need to create a PHP script that will handle the file upload. Create a new file called “upload.php” and add the following code:

PHP
<?php
if(isset($_FILES["file"]["type"])){
    $validextensions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 1000000)//Approx. 1MB
        && in_array($file_extension, $validextensions)) {
        if ($_FILES["file"]["error"] > 0){
            echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
        } else{
            if (file_exists("upload/" . $_FILES["file"]["name"])){
                echo $_FILES["file"]["name"] . " already exists. ";
            } else{
                move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
                echo "File uploaded successfully.";
            }
        }
    } else{
        echo "Invalid file format or size";
    }
}
?>
PHP

In this code, we have checked whether the uploaded file is an image with a valid extension and size. If the file meets the criteria, it is moved to the “upload” folder. If the file already exists in the folder, an error message is displayed.

Step 3: Add jQuery Code

Now, we need to add jQuery code to handle the upload progress bar. Add the following code to the “index.php” file:

JavaScript
$(document).ready(function(){
    var progress = $('#progress');

    $('#uploadForm').submit(function(event){
        event.preventDefault();

        var formData = new FormData($(this)[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            xhr: function(){
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(e){
                    if(e.lengthComputable){
                        var percent = Math.round((e.loaded / e.total) * 100);
                        progress.html(percent + '%');
                        progress.css('width', percent + '%');
                    }
                });
                return xhr;
            },
            success: function(response){
                progress.html('Upload Complete!');
                progress.css('width', '100%');
            },
            error: function(jqXHR, textStatus, errorThrown){
                progress.html('Error: ' + textStatus);
                console.log(errorThrown);
            }
        });
    });
});
JavaScript

In this code, we have added an event listener for the form submit event. When the form is submitted, we create a new FormData object to store the file data and use jQuery’s ajax() method to send the form data to the “upload.php” file.

We have also set the “async”, “cache”, “contentType”, and “processData” options to false to ensure that the file data is uploaded correctly.

The “xhr” option is used to get a reference to the XMLHttpRequest object and add an event listener for the “progress” event. This event is fired as the file is being uploaded and provides information about the upload progress. We use this information to update the progress bar in real-time.

Finally, we have added a “success” and “error” callback function to handle the server response. In the success function, we update the progress bar to indicate that the upload is complete. In the error function, we display an error message in case of any issues during the file upload.

If you have created all the files successfully time to test our code on browser.

javascript PHP
Share. Facebook Twitter Pinterest LinkedIn WhatsApp Reddit Tumblr Email
sarnathindia
  • Website

My name is Rohit Vadaviya and I am Programmer, Analyst And Blogger based in Baroda, India. I try to share some awesome scripts on my blog which I personally feel are useful for me as well as all developers, programmers and designers while working on any project.

Related Posts

Javascript March 1, 2023

Display location on google map from address using javascript google map api

PHP February 27, 2023

Read RSS feed of website (blog) using php

NodeJs February 27, 2023

Which is better: Node.js or PHP? Why?

PHP February 26, 2023

How to import excel file into mysql using php

Leave A Reply Cancel Reply

Top Posts

How to import excel file into mysql using php

February 26, 202329 Views

How to create chat application using node.js and socket.io

February 26, 202323 Views

Read RSS feed of website (blog) using php

February 27, 202318 Views

Subscribe to Updates

Get the latest tech news from FooBar about tech, design and biz.

Most Popular

How to import excel file into mysql using php

February 26, 202329 Views

How to create chat application using node.js and socket.io

February 26, 202323 Views

Read RSS feed of website (blog) using php

February 27, 202318 Views
Our Picks

How to Install Node.Js on Windows Machine

March 23, 2023

Image/File Upload with Progressbar Using PHP & Jquery

March 1, 2023

Display location on google map from address using javascript google map api

March 1, 2023

Subscribe to Updates

Get the latest creative news from FooBar about art, design and business.

Sarnath India
  • Home
  • About Us
  • Privacy Policy
  • Terms and Conditions
  • Disclaimer
  • DMCA
© 2023 ThemeSphere. Designed by ThemeSphere.

Type above and press Enter to search. Press Esc to cancel.