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

本文介绍了两种图片加载方法:直接使用img标签的src属性和通过XMLHttpRequest请求获取Blob对象进行显示。后者允许设置请求头,适用于跨域请求场景。文章还提供了一个jQuery优化示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

日常显示图片都诸如这种形式:直接使用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 对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值