接口返回图片流,前端如何展示

913 阅读1分钟

本篇文章主要是做技术积累使用,如有更好的方案,欢迎评论区提出哦~~

1、请求头设置 responseType 为 arraybuffer

{
    baseURL: process.env.VUE_APP_ENV !== "production" ? "/api" : "/api",
    timeout: 5000,
    headers: {
        uuid: "xxx",
    },
    responseType: "arraybuffer"
}

2、接口请求的地方处理返回数据并赋值给 img 的 url

request()
  .then(res => {
    return (
      "data:image/png;base64," +
      window.btoa(
        new Uint8Array(res).reduce(
          (data, byte) => data + String.fromCharCode(byte),
          ""
        )
      )
    );
  })
  .then(data => {
    this.url = data; //data可以直接放到img标签的src中
  });