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;
            }
          );

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

  • 相关阅读:
    node.js如何让前端请求时能跨域
    手把手教你使用webpack搭建vue框架
    手把手教你使用koa2
    react性能优化
    axios post 踩坑之 post传参
    小程序自定义左上角返回按钮跳转到指定界面
    webpack入门教程
    编写可维护的js代码
    js的严格模式
    vue短信验证性能优化写入localstorage中
  • 原文地址:https://www.cnblogs.com/dachengzizi/p/11775558.html
Copyright © 2011-2022 走看看