XHR上传进度从一开始就是100% [英] XHR Upload Progress is 100% from the start

查看:50
本文介绍了XHR上传进度从一开始就是100%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的XMLHTTPRequestUpload功能将一些文件上传到php脚本,它通常可以正常工作,上传开始,我得到完成响应等-但进度似乎不起作用.

I'm trying out the new XMLHTTPRequestUpload feature to upload some files to a php script, it mostly works fine, the upload starts, I get the finish response etc - but the progress doesn't seem to work.

查看event.loaded的值-在Firefox中,我似乎得到一个介于0和文件大小之间的随机值;在Chrome(我主要工作的地方)中,即使readystate尚未达到"4"并且开发人员工具"窗口仍显示文件正在加载,我仍能获得文件的总大小?

Looking that the event.loaded value - In firefox I seem to get a random value between 0 and the file size; in Chrome (where I'm mostly working) I get the total file size, even though the readystate hasn't reached '4' and the Developer Tools window still shows the file to be loading?

有什么想法吗?

这里是我的代码:

var xhr = new XMLHttpRequest()

xhr.upload.addEventListener('progress', function(event) {
    if (event.lengthComputable) {
        $('ajaxFeedbackDiv').innerHTML = event.loaded + ' / ' + event.total;
    }
}, false);

xhr.onreadystatechange = function(event) {
    if (event.target.readyState == 4) {
        updateFileList();
    }
};

xhr.open("POST", "_code/upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr(file);

非常感谢

推荐答案

我最近在设置XHR进行中事件的事件侦听器时也遇到了一些困难.我最终将其实现为一个匿名函数,该函数运行良好:

I also recently had some difficulty setting an event listener for XHR onprogress events. I ended up implementing it as an anonymous function, which works beautifully:

xhr.upload.onprogress = function(evt)
{
    if (evt.lengthComputable)
    {
        var percentComplete = parseInt((evt.loaded / evt.total) * 100);
        console.log("Upload: " + percentComplete + "% complete")
    }
};

但是,在此过程中,我偶然发现了很多个其他陷阱,因此很可能其中一个陷阱绊倒了我的事件侦听器.您所安装的设备与我的设置之间的唯一其他区别是,我使用的是xhr.sendAsBinary().

I stumbled across a lot of other gotchas along the way, though, so it's quite likely one of those was tripping up my event listener. The only other difference between what you've got there and my setup is that I'm using xhr.sendAsBinary().

这篇关于XHR上传进度从一开始就是100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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