js gets the binary stream image for rendering

Get a binary stream image

/**
 * 
 * @param imgUrl 获取图片的url的地址
 * @param defaultImgUrl 默认的一个图像显示的URL路径,本地存在 ,请求失败那就显示这个路径
 * @param token 
 * @param el 
 * @param cb 
 */
function getImage (imgUrl: string, defaultImgUrl: string, token: string, el: any, cb: any): void {
    
    
  const xhr: any = new XMLHttpRequest() //设置一个原生的ajax
  let flag: boolean = false
  xhr.open('get', imgUrl, true)//设置请求方式,请求地址,请求为异步进行
  xhr.setRequestHeader('Authorization', token)//设置请求头进行身份验证
  xhr.responseType = 'blob'//接受的响应体的类型为二进制流
  xhr.onload = function () {
    
    
    //此处的this指向为e,响应事件对象。
    if (this.status === 200) {
    
    
      if (this.response.type === 'text/xml' || this.response.type === '' || this.response.type === 'image/png' || this.response.type === 'image/jpeg') {
    
    
        const blob = this.response//收到这blob对象      
        const src = window.URL.createObjectURL(blob)//将blob对象转为本地资源的路径地址-指向该参数对象的路径,可以被src识别解析,        
        el.src = src //将指向地址赋值到img元素的src
        el.onload = () => {
    
    //等这个img对象完全加载src完毕就删除这个生成的blob对象。
          window.URL.revokeObjectURL(src)
        }
        flag = true //状态表示为加载成功
        if (cb) {
    
    
          cb(flag, el)
        }
      } else {
    
    
        el.src = defaultImgUrl
        flag = false
        if (cb) {
    
    
          cb(flag, el)
        }
      }
    } else {
    
    
      el.src = defaultImgUrl
      flag = false
      if (cb) {
    
    
        cb(flag, el)
      }
    }
  }
  //请求失败执行
  xhr.onerror = (err: Error): void => {
    
    
    console.log('请求失败:', err)
    el.src = defaultImgUrl
    flag = false
    if (cb) {
    
    
      cb(flag, el)
    }
  }
  //发送请求
  xhr.send()
}

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/128027991