I've been struggling to implement an upload progress bar using the XMLHttpRequest level 2 support for progress events in HTML5.
Most examples I come across show adding an event listener to the progress event like this:
req.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
console.log(percentComplete);
}
}, false);
However, I keep encountering the issue where event.lengthComputable is always false. This problem persists in browsers like Safari 5.1.7 and Firefox 12 on OSX.
My website is Django-based, and I face the same challenge on both my development and production environments.
Below is the complete code snippet I'm using for form uploads with jQuery:
form.submit(function() {
// Gather the data.
var data = form.serializeArray();
data.splice(0, 0, {
name: "file",
value: form.find("#id_file").get(0).files[0]
});
// Build the form data.
var fd = new FormData();
$.each(data, function(_, item) {
fd.append(item.name, item.value);
});
// Send the request.
var req = new XMLHttpRequest();
req.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
console.log(percentComplete);
}
}, false);
req.addEventListener("load", function(event) {
if (req.status == 200) {
var responseData = $.parseJSON(event.target.responseText);
if (responseData.success) {
console.log("Success!")
} else {
console.log("Failed!")
}
} else {
console.log("Something went wrong!")
}
}, false);
req.addEventListener("error", function() {
console.log("An error occurred!")
}, false);
req.open("POST", "/my-bar/media/add/");
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.send(fd);
// Prevent default submission.
return false;
});
I've spent hours troubleshooting this issue. Any assistance would be greatly appreciated!