vue 把 java 传过来的流文件 转成apk、xls等

1、在请求头设置:

export function downLoad(data) {
  return request({
    url: '/app/downLoad',
    method: 'post',
    responseType: 'blob', //最关键的部分
    headers: {
      'Content-Type': 'application/json'
    },
    data
  })
}

2、接口返回:

  

 

 

 3、处理流文件

downLoad({
          type: e
        }).then(res => {
          console.log(res);
          let data = res;
          const that = this;
          let fileReader = new FileReader();
          fileReader.onload = function() {
            try {
              // console.log(res);
              let jsonData = JSON.parse(this.result);
              if (jsonData.code) {
                that.$message({
                  message: jsonData.message,
                  type: 'error'
                })
                // 说明是普通对象数据,后台转换失败
              }
            } catch (err) {
              // console.log(res);
              // 解析成对象失败,说明是正常的流文件,转成 blob
              const blob = new Blob([res]);
         // 设置下载的文件名 const fileName
= '__UNI__' + formatDate(new Date(), 'yyyyMMddhhmmss') + '.apk'; //此次为文件名('__UNI__' + 当前时间 + .apk),若要 apk 转成 excel 或其他文件,设置文件后缀为 .xlsx 等 即可        // 创建 a 标签
        const elink
= document.createElement('a');
        // 添加 a 标签属性 elink.download
= fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); // 下载 URL.revokeObjectURL(elink.href); // 释放URL 对象 document.body.removeChild(elink); // 释放 a 标签 } }; fileReader.readAsText(data); }).catch(() => { that.loading = false })

4、示例:

 

 

 

 

  

 

posted @ 2020-07-31 11:50  小蘑菇123  阅读(686)  评论(0编辑  收藏  举报