接收二进制流(ArrayBuffer) ,并且显示二进制流图片

1.调用接口,返回二进制流数据

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {//
            var responseText = xhr.responseText;
            //返回二进制数据流
            console.log(responseText);
        }
    };
    xhr.open("GET", "/getData", true);
//需要设置
responseType
  xhr.responseType = "arraybuffer";
  xhr.send(null)

2. 把二进制数据转为base64

 function arrayBufferToBase64(buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }

3.显示图片

var response = xhr.response;
           var url= arrayBufferToBase64(response);
           document.getElementById('img').src='data:image/jpeg;base64,'+url;

完整代码

var xhr = new XMLHttpRequest();
    xhr.open("GET", "/getdata", true);
    xhr.responseType = "arraybuffer";
    xhr.send(null);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            //二进制数据流
            var response = xhr.response;
            var url= arrayBufferToBase64(response);
            document.getElementById('img').src='data:image/jpeg;base64,'+url;
        }
    };
   function arrayBufferToBase64(buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }
View Code

 

posted @ 2018-06-21 18:30  黑黑哈哈  阅读(2006)  评论(0编辑  收藏  举报