我使用ajax进行文件上传。
文件上传后,php 应该检查它(mime、大小、病毒(clamscan)等)——对于较大的文件,这需要几秒钟的时间。上传文件时,会出现 HTML5 <progress>
正在填充,当文件准备好并且 PHP 开始检查时,进度应切换为不确定。我想到了一些方法来做到这一点(这两种方法都不起作用):
检查 upload.onload 事件
xhr.upload.addEventListener("load", function (e) {
$("#uploadprogress").attr("value", false);
$("#uploadprogress").attr("max", false);
$("#progress").text("Checking file...");
});
这不起作用,因为 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 开始处理文件
还有其他可能性检查这个吗?
最佳答案
您要监听的事件是 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.
}
});
关于javascript - XMLHttpRequest Level 2 - 确定上传是否完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15418608/