7

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).

user2695688
  • 136
  • 1
  • 4

3 Answers3

3

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 + '%'
}
Kiyan
  • 2,155
  • 15
  • 15
0

I had the same problem like yours, then I tried my page from another computer, everything just went OK, I did use Chrome's network throttling to simulate a slow internet connection but it seems that there are still something different from real situation

Yangxiao Ou
  • 115
  • 6
0

Because the server or the gateway cache the request data immediately, write the file data to the disk or memory. At this time, the file data progress indeed is 100%. But the server's logic code has not yet finish process the file data which is just cached in the server.

jamesxiang
  • 708
  • 5
  • 10