使用vue 对二进制文件 实现下载,blob对象

有很多网站会涉及到文件下载,这里我们使用axios 发送请求 接受数据

第一步 模仿jQ 封装接口

 Vue.prototype.$xlsx_post = function (url, data, fun, err) {
  var userName = getCookie("username")
  axios({
      method: 'post',
      url: url,
      responseType: "blob",
      headers: {
        'Authorization': userName ? userName.token_type + userName.access_token : "Basic emh4eTp6aHh5"
      },
      data: data
    }).then(function (res) {
      if (fun) {
        fun(res)
      }
    })
    .catch(function (error) {
      if (err) {
        err(error)
      }
    });
}

注意 : responseType 要设置为 blob 告诉服务器你期望的响应格式。

第二步 发送请求 接受数据

 this.$xlsx_post(
        `/rsgl/rstrainperson/exportExcel`,
        {
          trainId: this.$route.query.id,
          userId: this.multipleSelection.join(",")
        },
        res => {
          const blob = new Blob([res]); // 创建blob对象
          const fileName = "培训管理.xlsx";
          const elink = document.createElement("a"); // 创建的标签
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob); // 创建url
          document.body.appendChild(elink); // 把 创建的标签追加到body里
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink); // 移除标签
          this.$message({
            message: "导出成功!!!",
            type: "success"
          });
          this.$refs.multipleTable.clearSelection();
        },
        err => {
          this.$message.error("服务器错误");
          throw err;
        }
      );

好了, 希望对大家有所帮助