Best way to capture an upload’s progress

Asked

Viewed 94 times

0

Hello, I would like to know the best way to capture the progress of an upload using Xmlhttprequest .

  • what would be the xhr?

  • Xmlhttprequest, I’ll edit the question

  • Upload via Xmlhttprequest I didn’t know. You can give an example?

1 answer

2


When you work with upload and with api XMLHttpRequest, you have access to the object XMLHttpRequest.upload. With this object, just add the event progress 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.