File upload progress bar with jQuery
Note: This question is related to the jQuery form plugin. If you are searching for a pure jQuery solution, start here. There is no overall jQuery solution for all browser. So you have to use a plugin. I am using dropzone.js, which have an easy fallback for older browsers. Which plugin you prefer depends on your needs. There are a lot of good comparing post out there.
From the examples:
jQuery:
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
html:
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
you have to style the progressbar with css...
I've done this with jQuery only:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
if (percentComplete === 100) {
}
}
}, false);
return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});
I have used the following in my project. you can try too.
ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
if (ajax.status) {
if (ajax.status == 200 && (ajax.readyState == 4)){
//To do tasks if any, when upload is completed
}
}
}
ajax.upload.addEventListener("progress", function (event) {
var percent = (event.loaded / event.total) * 100;
//**percent** variable can be used for modifying the length of your progress bar.
console.log(percent);
});
ajax.open("POST", 'your file upload link', true);
ajax.send(formData);
//ajax.send is for uploading form data.