我正在使用ajax进行文件上传。文件上传后,php应该检查它(mime,大小,病毒(clamscan)等)-对于较大的文件,这需要花费几秒钟的时间。当文件上传时,<progress>正在填充HTML5 ,当文件准备好并且PHP开始检查时,进度应该切换为不确定。我认为对的方式来做到这一点(这两者做 不 工作):
<progress>
检查upload.onload事件
xhr.upload.addEventListener("load", function (e) { $("#uploadprogress").attr("value", false); $("#uploadprogress").attr("max", false); $("#progress").text("Checking file..."); });
这行不通,因为onload-event在请求准备就绪时触发,而不是在上传准备就绪时触发。
onload
检查上传进度百分比是否= 100%
xhr.upload.addEventListener("progress", function (e) { if (e.lengthComputable && e) { p = (e.loaded / e.total); if (p==1) { $("#uploadprogress").attr("value", false); $("#uploadprogress").attr("max", false); $("#progress").text("Checking file..."); } else { var percent = Math.ceil(p * 1000) / 10; $("#uploadprogress").val(e.loaded); $("#uploadprogress").attr("max", e.total); $("#progress").text("Uploading... " + percent + "%"); } } } });
这是行不通的,因为上载百分比有时会停在大约 97%,尽管上传完成并且PHP开始处理文件
还有另一种可能性检查吗?
您要监听的事件readystatechange在XHR对象上(不在XHR.upload上)。readyState是4当上载完成发送 ,并 在服务器关闭连接 。loadend/ load在上载完成时触发,无论服务器是否关闭连接。仅供参考,以下是您可以收听以及触发的事件:
readystatechange
readyState
4
loadend
load
var xhr = new XMLHttpRequest(); // ... // do stuff with xhr // ... xhr.upload.addEventListener('loadstart', function(e) { // When the request starts. }); xhr.upload.addEventListener('progress', function(e) { // While sending and loading data. }); xhr.upload.addEventListener('load', function(e) { // When the request has *successfully* completed. // Even if the server hasn't responded that it finished. }); xhr.upload.addEventListener('loadend', function(e) { // When the request has completed (either in success or failure). // Just like 'load', even if the server hasn't // responded that it finished processing the request. }); xhr.upload.addEventListener('error', function(e) { // When the request has failed. }); xhr.upload.addEventListener('abort', function(e) { // When the request has been aborted. // For instance, by invoking the abort() method. }); xhr.upload.addEventListener('timeout', function(e) { // When the author specified timeout has passed // before the request could complete. }); // notice that the event handler is on xhr and not xhr.upload xhr.addEventListener('readystatechange', function(e) { if( this.readyState === 4 ) { // the transfer has completed and the server closed the connection. } });