zoukankan      html  css  js  c++  java
  • 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字符串
          }
        }
      })
  • 相关阅读:
    Codeforces Round #348 (VK Cup 2016 Round 2, Div. 2 Edition) D. Little Artem and Dance
    HDU 5521 Meeting 最短路
    BZOJ 1051: [HAOI2006]受欢迎的牛 强连通缩点
    P2661 信息传递 强连通分量
    Codeforces Round #343 (Div. 2) C. Famil Door and Brackets
    HDU 4859 海岸线 最小割
    HDU 4162 Shape Number
    Codeforces Round #355 (Div. 2) D. Vanya and Treasure dp+分块
    bzoj 1295: [SCOI2009]最长距离 暴力+bfs最短路
    Codeforces Round #222 (Div. 1) C. Captains Mode 对弈+dp
  • 原文地址:https://www.cnblogs.com/asker009/p/13936167.html
Copyright © 2011-2022 走看看