后端返回图片二进制流,前端处理

//vue中
let that = this;
      that.$http.get("url....", {
        responseType: "arraybuffer",
      }).then(function (response) {
        //将从后台获取的图片流进行转换
        return 'data:image/png;base64,' + btoa(
          new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
        );
      }).then(function (data) {
        //接收转换后的Base64图片
        that.validCodeImg = data;
      }).catch(function (error) {
        // this.$message.error(error);
      })

1. 原生页面(2种方法)

(1)

       dom:

       js: getCode()方法中 将请求链接赋值给dom的src(注意防止取缓存,需要在src上拼接一个随机数)

(2)

       这种方法中window.URL.createObjectURL是不兼容IE9的 ,所以....

var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "...", true);
            xmlhttp.responseType = "blob";
            xmlhttp.onload = function() {
                if (this.status == 200) {
                    var blob = this.response;
                    var url = window.URL.createObjectURL(blob);
                    document.getElementById("validCode").src = url;
                }
            };
            xmlhttp.send();

 

你可能感兴趣的:(js)