How to implement a progress bar for file uploads using jQuery



Image not found!!


Implementing a progress bar for file uploads using jQuery typically involves using the XMLHttpRequest object to handle the file upload asynchronously and updating the progress bar based on the upload progress. Here's a basic example:

  1. HTML: Include the necessary HTML elements for the file input and 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 Progress Bar</title> <!-- Include jQuery --> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <input type="file" id="fileInput" /> <button onclick="uploadFile()">Upload</button> <div id="progressBarContainer"> <div id="progressBar"></div> <div id="progressLabel">0%</div> </div> <script src="script.js"></script> </body> </html>
  1. JavaScript (script.js): Write the JavaScript code to handle the file upload and update the progress bar.
js
function uploadFile() { var fileInput = document.getElementById('fileInput'); var file = fileInput.files[0]; if (file) { var formData = new FormData(); formData.append('file', file); $.ajax({ url: 'your_upload_endpoint.php', // Replace with your server-side file upload endpoint type: 'POST', data: formData, processData: false, contentType: false, xhr: function () { var xhr = new XMLHttpRequest(); // Upload progress xhr.upload.addEventListener('progress', function (e) { if (e.lengthComputable) { var percent = (e.loaded / e.total) * 100; updateProgressBar(percent); } }, false); return xhr; }, success: function (response) { console.log('File uploaded successfully:', response); }, error: function (error) { console.error('File upload failed:', error); } }); } else { console.error('No file selected.'); } } function updateProgressBar(percent) { var progressBar = $('#progressBar'); var progressLabel = $('#progressLabel'); progressBar.width(percent + '%'); progressLabel.text(percent.toFixed(2) + '%'); }

This example assumes you have a server-side endpoint (e.g., PHP script) to handle file uploads. Replace 'your_upload_endpoint.php' with the actual endpoint.

Remember to handle file uploads securely on the server side and validate user input to prevent potential security issues.