XMLHttpRequest upload.onprogress instantly complete

偶尔善良 提交于 2019-12-19 07:23:07

问题


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


回答1:


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 + '%'
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/18310038/xmlhttprequest-upload-onprogress-instantly-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!