vue项目,axios请求后端的图片文件流

1、接收的是字节数组

axios
  .get('/avatar', {
    params: param,
    responseType: 'arraybuffer'
  })
  .then(response => {
    return 'data:image/png;base64,' + btoa(
      new Uint8Array(response.data)
        .reduce((data, byte) => data + String.fromCharCode(byte), '')
    );
  }).then(data => {
    ...
  })

2、项目中的后端

    @GetMapping(value = "/avatar")
    public byte[] getUserAvatar() {
        return this.sysUserService.getUserAvatarByUserId(SecurityUtils.getCurrentUserId());
    }

    public byte[] getUserAvatarByUserId(String id) {
        SysUserAvatar userAvatar = this.sysUserAvatarDao.queryById(SecurityUtils.getCurrentUserId());
        if(userAvatar == null) return new byte[0];
        File file = new File(userAvatar.getPath());
        if(!file.exists()) return new byte[0];

        FileInputStream inputStream = null;
        byte[] bytes = null;
        try {
            inputStream = new FileInputStream(file);
            bytes = new byte[inputStream.available()];
            int read = inputStream.read(bytes, 0, inputStream.available());
            log.info("读取用户头像数据:"+read+"字节");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(StatusCode.ERROR,"读取文件错误");
        }finally {
            IoUtil.close(inputStream);
        }

        return bytes;

    }

3、vue项目中的前端

// 获取头像图片的字节数组byte[]
export function getAvatar() {
  return request({
    url: `api/users/avatar`,
    method: 'get',
    responseType: 'arraybuffer'
  })
}

 

    getUserAvatar() {
      getAvatar().then(res => {
        this.AvatarData = 'data:image/png;base64,' + btoa(
          new Uint8Array(res.data)
            .reduce((data, byte) => data + String.fromCharCode(byte), ''))
      })
    }
<img :src="user.avatar ? AvatarData : Avatar" title="点击上传头像" class="avatar">

 4、补充,要是后端是不是字节数组返回,而是通过response的blob类型返回

// 使用axios请求上传接口
 axios({
    method: 'get',
    url: url, // 请求地址
    responseType: 'blob' // 设置接收格式为blob格式
  }).then(res => {
    // console.log(res)
    if (res && res.data && res.data.size) {
      const dataInfo = res.data
      let reader = new window.FileReader()
      // 使用readAsArrayBuffer读取文件, result属性中将包含一个 ArrayBuffer 对象以表示所读取文件的数据
      reader.readAsArrayBuffer(dataInfo)
      reader.onload = function (e) {
        const result = e.target.result
        const contentType = dataInfo.type
        // 生成blob图片,需要参数(字节数组, 文件类型)
        const blob = new Blob([result], { type: contentType })
        // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
        const url = window.URL.createObjectURL(blob)
        console.log(url) // 产生一个类似 blob:d3958f5c-0777-0845-9dcf-2cb28783acaf 这样的URL字符串
      }
    }
  })

 

posted @ 2020-11-06 11:54  我是属车的  阅读(6362)  评论(0编辑  收藏  举报