vue2前端调接口下载(导出)后端返回.zip压缩文件流

1、接口api

// 三级教育档案导出
export function searchPersonnelHousInfoExport(data) {
  return request({
    url: train + '/fileExport/controller/export/personalProfile',
    method: 'post',
    data: data,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json; application/octet-stream'
    }
  })
}

调用:

async exportFn() {
      let upload_loading = this.$loading({
        lock: true,
        text: '数据导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      });
      let params = {
        userId: this.selectData,
        startTime: this.queryParams.startTime,
        endTime:this.queryParams.endTime
      }
      await searchPersonnelHousInfoExport(params).then(res=>{
        upload_loading.close();
        if(res){
          this.fileHandleCompressed(res, '三级教育档案导出.zip');
        }else{
          this.$modal.msg('下载文件出现错误,请联系管理员!');
        }
      }).catch(err=>{
        upload_loading.close();
      });
    }

// 文件流转为zip
    fileHandleCompressed(data, fileName) {
      let blob = new Blob([data], { type: 'application/zip,charset=utf-8'})//此处必须添加
      let url = window.URL.createObjectURL(blob);
      const link = window.document.createElement('a'); // 创建a标签
      link.href = url;
      link.download = fileName; // 重命名文件
      link.click();
      URL.revokeObjectURL(url); // 释放内存
    },

注意:使用文件流时不能引入mock,否则会致使文件流乱码,导致无法正常导出为zip格式的压缩包文件。

 

posted on 2023-12-19 16:36  小虾米吖~  阅读(1045)  评论(0编辑  收藏  举报