仅在完成时才触发JS ProgressEvent [英] JS ProgressEvent is only fired when finished

查看:224
本文介绍了仅在完成时才触发JS ProgressEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使上传进度栏正常工作时遇到一些问题.

I am having some problems getting my upload progress bar to work properly.

根据XMLHttpRequest Level 2规范,我为loadstart和progress附加了事件侦听器,如下所示:

According to the XMLHttpRequest Level 2 specs, I attached event listeners for loadstart and progress like this:

var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('loadstart', function(e) {progressCallback(0);});
xhr.upload.addEventListener('progress', function (e) {
    progressCallback(e.loaded / e.total);
});    

$.ajax({
    url: url,
    type: 'POST',
    processData: false,
    contentType: false,
    data: formData,
    xhr: function () {
        return xhr;
    }
}).done(function (data) {
    // Finish stuff
})

文件已正确上传,但仅在请求完成100%(e.total == e.loaded)后才调用进度监听器

The file is correctly uploaded but the progress listener is only called once the request is finsished with 100% (e.total == e.loaded)

上面的代码有什么问题吗,还是有必要以任何特殊方式配置服务器?

Is anything wrong with the code above or is it necessary to configure the server in any special way?

推荐答案

当无法确定文件的总大小时,e.loadede.total为零.您可以在progress函数中对此进行检查:

When the total size of the file can't be determine, e.loaded and e.total are zero. You can check this inside your progress function:

if (evt.lengthComputable) {
    progressCallback(e.loaded / e.total);
}

服务器还必须发送规范<中定义的Content-Length /a>:

The server must also send Content-Length which is defined in the specification:

如果通过Content-Length标头知道HTTP实体主体的长度,则将lengthComputable属性初始化为true,并将total属性初始化为该长度.

If the length of the HTTP entity body is known through the Content-Length header, initialize the lengthComputable attribute to true and initialize the total attribute to the length.

请注意,进度栏不适用于file:协议.

Please also notice that the progress bar don't work with the file: protocol.

我真的可以推荐非常广泛的Mozilla文档-使用XMLHTTPRequest Mozilla文档

I can really recommend the Mozilla docs which are very extensive - Using XMLHTTPRequest Mozilla Docs

这篇关于仅在完成时才触发JS ProgressEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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