VUE使用Blob下载

vue项目使用axiox封装http请求,需求是实现下载功能

为了安全要携带用户Token以及需要走封装的拦截器,所以只能使用封装的http请求来下载

查了一下需要用Blob流来下载

以下是我的实现方案(如有不足,欢迎大佬指正!):

下载按钮执行:

/** 导出按钮操作 */
    async answerFileDownloadFun(item) {
      try {
        let res = await answerFileDownload(item.questionNaireId, item.anwserId);
        debugger;
        if (res.data.type === "application/octet-stream") {
          // 获取http头部的文件名信息,若无需重命名文件,将下面这行删去
          const fileName = res.headers["content-disposition"].split("=")[1];
          /* 兼容ie内核,360浏览器的兼容模式 */
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            const blob = new Blob([res.data], {
              type: "application/zip"
            });
            window.navigator.msSaveOrOpenBlob(
              blob,
              decodeURIComponent(fileName)
            );
          } else {
            /* 火狐谷歌的文件下载方式 */
            const blob = new Blob([res.data], {
              type: "application/zip"
            });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement("a"); // 创建a标签
            link.href = url;
            link.download = decodeURIComponent(fileName); // 文件重命名,若无需重命名,将该行删去
            link.click();
            URL.revokeObjectURL(url); // 释放内存
          }
        } else {
          const reader = new FileReader();
          reader.onload = function(event) {
            const msg = JSON.parse(reader.result).data;
          };
          reader.readAsText(res.data);
        }
      } catch (error) {
        console.error(error);
      }
    },

api.js设置请求路径:

// 下载附件
export function answerFileDownload(questionNaireId,anwserIds) {
  return request({
    url: '/questionnaire/questionNaireAnswer/answerFileDownload/' + questionNaireId + '/' + anwserIds,
      method: 'get',
    noFetchTime:true//设置超长超时时间
  })
}

封装请求request.js(设置超时时间及下载类型):

if (config.noFetchTime) {
        config.timeout = 200000000000000000
        config.responseType = "blob"
    }

第一次发布文章,请大家多多指正

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值