XMLHttpRequest upload.onprogress 即时完成 [英] XMLHttpRequest upload.onprogress instantly complete

查看:14
本文介绍了XMLHttpRequest upload.onprogress 即时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有进度表的 HTML5 制作文件上传器.这是我的代码:

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.

我是否遗漏了一些明显的东西?据我所知,这发生在我的所有浏览器(IE10、Chrome 28、FF22)上.

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

推荐答案

这是我的代码,对我来说很好用:

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

这篇关于XMLHttpRequest upload.onprogress 即时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆