axios中设置了response:blol后,如何处理json对象

axios中文件下载

上传文件后台校验,若失败则下载文件
let loading = this.$common.loading("正在上传");
      let form = new FormData();
      let headers = {
        responseType: "blob"
      };
      form.append("file", e.file);
      this.$axios
        .post(e.action, form, headers)
        .then(res => {
          loading.close();
          let _this = this;
          let reader = new FileReader();
          reader.readAsText(res, "utf-8");
          reader.onload = function() {
            try {
              let a = JSON.parse(this.result);
              let b = a.data.totel;
              let c = b.split(",");
              _this.$message.success(
                `总共${c[0]}条, 成功${c[1]}条, 重复${c[2]}条(数据库中已存在))`
              );
            } catch (error) {
              let blob = new Blob([res]);
              let objectUrl = URL.createObjectURL(blob);
              let a = document.createElement("a");
              a.href = objectUrl;
              a.download = "错误样本.xls";
              //下面这个写法兼容火狐
              a.dispatchEvent(
                new MouseEvent("click", {
                  bubbles: true,
                  cancelable: true,
                  view: window
                })
              );
              window.URL.revokeObjectURL(blob);
            }
          };

reponseType设为blob后如何校验是否正确与否

抽离上面的东东
后台处理逻辑为成功返回json,失败返回流提供下载
思路将blob转化为json,转换成功则上传成功,转换失败为流下载文件
let reader = new FileReader();
          reader.readAsText(res, "utf-8");
          reader.onload = function() {
            try {
              let a = JSON.parse(this.result);
              let b = a.data.totel;
              let c = b.split(",");
              _this.$message.success(
                `总共${c[0]}条, 成功${c[1]}条, 重复${c[2]}条(数据库中已存在))`
              );
            } catch (error) {
              let blob = new Blob([res]);
              let objectUrl = URL.createObjectURL(blob);
              let a = document.createElement("a");
              a.href = objectUrl;
              a.download = "错误样本.xls";
              //下面这个写法兼容火狐
              a.dispatchEvent(
                new MouseEvent("click", {
                  bubbles: true,
                  cancelable: true,
                  view: window
                })
              );
              window.URL.revokeObjectURL(blob);
            }
        }    
参考文章 https://www.cnblogs.com/qilj/p/11950517.html
posted @ 2020-01-18 21:48  萝卜爱吃肉  阅读(744)  评论(0编辑  收藏  举报