How to create a dynamic progress bar for a file upload using jQuery



Image not found!!

Creating a dynamic progress bar for a file upload using jQuery involves a combination of HTML, JavaScript, and possibly a server-side language like PHP for handling the file upload. Here's a simple example using HTML, jQuery, and a hypothetical server-side script in PHP:

  1. HTML Markup: Create a basic HTML structure with a form for file upload and a div to display the progress bar.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload with Progress Bar</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <form id="uploadForm" enctype="multipart/form-data"> <input type="file" name="file" id="fileInput"> <button type="button" onclick="uploadFile()">Upload</button> </form> <div id="progressBar"> <div id="progress"></div> <div id="progressText">0%</div> </div> <script src="script.js"></script> </body> </html>
  1. JavaScript (script.js): Create a JavaScript file to handle the file upload and update the progress bar dynamically using jQuery.
javascript
function uploadFile() { var formData = new FormData($("#uploadForm")[0]); $.ajax({ url: "upload.php", // Replace with the actual server-side script handling the file upload type: "POST", data: formData, processData: false, contentType: 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").css("width", percent + "%"); $("#progressText").text(percent + "%"); } }, false); return xhr; }, success: function (response) { // Handle the server response console.log(response); }, error: function (error) { console.log(error); } }); }
  1. PHP (upload.php): Create a server-side script to handle the file upload. This is just a basic example; you should add proper error handling, file validation, and security measures based on your requirements.
php
<?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { echo "File uploaded successfully!"; } else { echo "Error uploading file."; } ?>

Remember to adjust the paths and filenames as needed, and ensure that the server has the necessary permissions for file uploads. Also, consider adding security measures like file type validation and sanitization based on your application's requirements.