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">

 

上一篇:使用FTPClient循环获取inputStream值为null


下一篇:Java Unit 测试中如何获得 resources 中的文件