ajax请求二进制流图片并渲染到html中img标签

日常显示图片都诸如这种形式:直接使用img的src属性

<img src="图片路径、地址" alt="" />

以上方法无法在获取图片请求中设置请求头(headers)中字段

方法二:

var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://10.10.0.62:10001/api/charge/admin/v1/image/code",true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function(){
    console.log(this);
    if (this.status == 200) {
        var blob = this.response;
        var img = document.createElement("img");
        img.onload = function(e) {
            window.URL.revokeObjectURL(img.src); 
        };
        img.src = window.URL.createObjectURL(blob);
        document.body.appendChild(img); 
    }
}
xmlhttp.send();
默认情况下,在发送XHR请求(request)的同时,还会发送下列头部信息:
Accept:浏览器能够显示的字符集。
Accept-Charset:浏览器能够显示的字符集。
Accept-Encoding:浏览器能够处理的压缩编码。
Accept-Language:浏览器当前设置的语言。
Connection: 浏览器与服务器之间的连接类型。
Cookie:当前页面设置的任何cookie
Host:发出请求的页面所在域。
Referer:发出请求的页面的URL.(该单词正确拼法是referrer)
User-Agent:浏览器的用户代理字符串。

jquery优化版:

function imgFun (url, auth, img) {
                    var windowUrl = window.URL || window.webkitURL;//处理浏览器兼容性
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET", url, true);
                    xhr.responseType = "blob";
                    xhr.setRequestHeader("Authorization", 'Bearer ' + auth.token);
                    xhr.onload = function () {
                        console.log(this);
                        if (this.status == 200) {
                            var blob = this.response;
                            $(img).load(function (e) {
                                windowUrl.revokeObjectURL(img.src);
                            }).attr("src", windowUrl.createObjectURL(blob));
                        }
                    }
                    xhr.send();
                }

imgFun("/common/download/rgPhoto/" + d.result, auth, $("#rgPhotoImg");

参考:

1.ajax请求二进制流图片并渲染到html中img标签

2.XML DOM - XMLHttpRequest 对象

原文地址:https://www.cnblogs.com/liaojie970/p/8819051.html