使用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
        }));

最佳答案

我只是通过一些旧的代码来做到这一点。为了上传,我这样做了

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())

10-05 20:48
查看更多