当responseType设置为arraybuffer时,XMLHttp请求不返回响应

时间:2018-06-23 01:05:22

标签: javascript node.js xmlhttprequest arraybuffer

我正在尝试从本地文件读取jpg图像并将其作为数组缓冲区获取。当我在Chrome调试器中查看时,只能看到responseTextresponseStatusresponseXML,但没有任何响应。 responseText确实有我的数据,但似乎有些损坏(因为它与我在图像文件的二进制转储中看到的不匹配)。有谁知道1)为什么将响应类型设置为XMLHttpRequestarraybuffer不返回响应字段? 2)如果必须使用responseText字段,如何确保收到的图像二进制数据与原始文件中的二进制数据完全匹配?谢谢。 这是我读取图像的代码:

function loadXHR(url) {

    return new Promise(function(resolve, reject) {
        try {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.responseType = "arraybuffer";  //I changed "blob" to this
            xhr.onerror = function() {reject("Network error.")};
            xhr.onload = function() {
                if (xhr.status === 200) {console.log("response is : ", xhr.responseText[0], xhr.responseText[1]);
                    resolve(xhr.responseText)
                }
                else {reject("Loading error:" + xhr.statusText)}
            };
            xhr.send(null);
        }
        catch(err) {reject(err.message)}
    }).catch(()=> {"Promise failed with error"});
}

当我尝试resolve(xhr.response)时失败,因为xhr.response未定义。

0 个答案:

没有答案