我使用ajax进行文件上传。上传文件后,php应该检查它(mime、大小、病毒(翻盖扫描)等等)--对于较大的文件,这需要几秒钟的时间。当文件上传时,一个HTML5 <progress>正在填充,当文件准备就绪,并且PHP开始检查时,进度应该切换到不确定。我想出了做这件事的方法(这两种方法都行不通):
检查upload.onload事件
xhr.upload.addEventListener("load", function (e) {
$("#uploadprogress").attr("value", false);
$("#uploadprogress").attr("max", false);
$("#progress").text("Checking file...");
});这不起作用,因为当请求准备就绪时,onload-event最不方便,而不是在上传准备就绪时。
检查上传进度百分比= 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开始处理文件
还有另一种可能性在检查吗?
发布于 2013-03-19 03:40:22
您想要侦听的事件是XHR对象上的readystatechange (而不是XHR.upload)。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.
}
});发布于 2013-03-19 00:52:24
这是相对已知的hTML5规范的下降,当时他们可以轻松地扩展它以添加信息,如timeRemaining和transferSpeed。
你有没有考虑过用math.round而不是math.ceil来代替var percent,这样你就可以在一种模糊的气氛中烘焙,这样就能避免几个百分点的损失?
您还应该为loadComplete添加另一个侦听器,即使在后端已经完成了,但用户界面仍然停留在<100%的位置:
//only fires once
xhr.addEventListener('loadend', uploadComplete, false);
function uploadComplete(event) {
console.log('rejoice...for I have completed');
//do stuff
}发布于 2013-03-20 09:08:25
检查readyState,if(readyState==4) {//it has finished, put code here}
https://stackoverflow.com/questions/15418608
复制相似问题