Hello, I would like to know the best way to capture the progress of an upload using XMLHttpRequest.
Hello, I would like to know the best way to capture the progress of an upload using XMLHttpRequest.
When you work with the upload and with api
XMLHttpRequest
, you have access to the XMLHttpRequest.upload
object. With this object, simply add the progress
event to capture the total bytes that were sent and the total bytes of the file.
In this way we can perform the calculation: n = (total de bytes enviados * 100) / total de bytes do arquivo
And to return an integer, we use the method Math.floor(n)
<!DOCTYPE hml>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="file" /><br><br>
<button>Send</button>
<script>
const inputFile = document.querySelector("input");
const button = document.querySelector("button");
const req = new XMLHttpRequest();
req.upload.addEventListener("progress", function(progress) {
if ( progress.lengthComputable ) {
console.log( Math.floor((progress.loaded * 100) / progress.total) + "%" );
}
});
button.addEventListener("click", function() {
let formData = new FormData();
formData.append("file", inputFile.files[0]);
req.open("POST", "index3.php", true);
req.send(formData);
});
</script>
</body>
</html>