zoukankan      html  css  js  c++  java
  • 使用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;
            }
          );

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

  • 相关阅读:
    ROS探索总结(三十一)——ros_control
    ROS探索总结(四十二)——twist_mux多路切换器
    综合面试十大维度解析
    面试官实战-2-业务面试官必须掌握的面试方法及实战演练
    面试官实战-1-素质测评起源和分析
    好的招聘官
    好的候选人
    专题工作模板
    月周报模板
    学习记录模板
  • 原文地址:https://www.cnblogs.com/dachengzizi/p/11775558.html
Copyright © 2011-2022 走看看