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:
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>
javascriptfunction 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);
}
});
}
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.