使用XMLHttpRequest获取二进制数据显示图片

原创
2017/02/12 16:22
阅读数 1K

需求场景

图片需要使用接口动态获取,请求接口时必须携带特定请求头

例:

接口地址为:http://img.cn/jpg/1

指定请求头:X-Requested-With=OpenAPIRequest

如果简单使用<img src='http://img.cn/jpg/1'>,没携带特定请求头,请求失败

解决方案

var xhr = new XMLHttpRequest()

xhr.onreadystatechange = function () {
  var blob
  if(xhr.readyState === 4){

    // 使用URL.createObjectURL将Blob对象转换为可访问的url地址
    var src = URL.createObjectURL(xhr.response)
    document.getElementById('img').src = src
  }
}

xhr.open('GET','http://img.cn/jpg/1', true)

// 设置响应数据格式为Blob对象
xhr.responseType = 'blob'

// 设置请求头
xhr.setRequestHeader('X-Requested-With', 'OpenAPIRequest')

xhr.send()

参考文献

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
返回顶部
顶部