XMLHttpRequest接受流请求,显示图片

假如后台的接口,我们本来是返回一个图片,但是有些情况下,接口直接返回一个stream,那么如何通过AJAX显示在页面?

var xhr = new XMLHttpRequest();    
    xhr.open("get", "http://localhost:8080/getImage", true);
    xhr.responseType = "blob";
    xhr.onload = function() {
        if (this.status == 200) {
            var blob = this.response;
            var img = document.createElement("img");
            img.src = window.URL.createObjectURL(blob);
    $("#img").html(img);
 } };
xhr.send();

细节中特别的地方就是blob,通过这个类型来处理stream

原文地址:https://www.cnblogs.com/greys/p/10950706.html