Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest upload.onprogress instantly complete

I'm trying to make a file uploader with HTML5 with a progress meter. Here's my code:

<!DOCTYPE html>
<html>
<head>
    <title>Test Progress Meter</title>
    <script type="text/javascript">

        function submitFile(){
            var blobOrFile = document.getElementById("fileInput").files[0];

            var xhr = new XMLHttpRequest();

            xhr.onload = function(e) {
                alert("finished!");
            };

            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    document.getElementById("statusBox").innerHTML = e.loaded + " / " + e.total;
                }
            };

            xhr.open('POST', 'test.php', true);

            xhr.send(blobOrFile);
        };


    </script>
</head>
<body>
    <input type="file" id="fileInput" onchange="submitFile();" />
    Status: <span id="statusBox"></span>
</body>
</html>

Basically, on all of my browsers, when I choose a file to upload, the progress event fires and immediately shows the entire transfer as complete. Then it sits there while the file actually uploads, and depending on the file, after some seconds/minutes, the script alerts and shows the proper response from the server.

Am I missing something obvious? As far as I can see, this happens on all my browsers (IE10, Chrome 28, FF22).

like image 389
user2695688 Avatar asked Aug 19 '13 09:08

user2695688


1 Answers

this is my code and it's work fine for me:

xhr.upload.onprogress = function(e){
    var done = e.position || e.loaded, total = e.totalSize || e.total
    var present = Math.floor(done/total*100)
    document.getElementById('status').innerHTML = present + '%'
}
like image 149
Kiyan Avatar answered Oct 17 '22 08:10

Kiyan