JS XHR JSON有效负载上传进度

时间:2018-10-18 03:10:15

标签: javascript upload xmlhttprequest

使用XHR上载较大的JSON有效负载字符串时能获得进度的任何方法吗?

在我的代码中,一旦完成,它只会打印100%,即使json有效负载大小= 30MB

let xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
        xmlhttp.addEventListener("progress", function (evt) {
            console.log(evt.lengthComputable); // false
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                console.log((Math.round(percentComplete * 100) + "%"));
            }
        }, false);
        xmlhttp.onreadystatechange = (event) => {
            if (xmlhttp.readyState === 4 && xmlhttp.status >= 200 && xmlhttp.status <= 299) {
                let res = JSON.parse(xmlhttp.responseText);
                if (typeof this.options.onVideoGetsUploaded === "function") {
                    console.log('success')
                }
            } else if (xmlhttp.readyState === 4 && xmlhttp.status >= 400 && xmlhttp.status <= 550) {
                //error while uploading
                console.log(xmlhttp.statusText)
            }
        };
        xmlhttp.open("POST", this.options.uploadEndPoint, true);
        xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xmlhttp.send(JSON.stringify({
            data: base64data
        }));

2 个答案:

答案 0 :(得分:1)

我刚刚完成了一些旧代码。对于上传,我做到了

var request = new XMLHttpRequest();

// before opening your request
request.upload.onprogress = function(e) {
    // progress in % is: Number(e.loaded / e.total * 100)
};

// open and send request

似乎很奇怪,我记得花了几个小时试图弄清楚这一点。也许您也可以这样做:

request.upload.addEventListener(“progress”, callback())

答案 1 :(得分:0)

您可以在请求中设置content-length标头,然后evt.lengthComputable可以为true。