前端vue实现导出功能:当后端给你返回的是文件流时,你要如何导出?

前言:

当有一个需求,让你导出文件、后台有时候会给你返回一个下载链接,做个按钮点一下发个请求就ok了
但如果给你返回文件流,我们要怎么对文件流处理呢?


解决方案:

话不多说、我们直接上代码:从axios开始看就ok————其他的我也要做个记录

 async download() {
 		//判断导出文件的时间区间
      let start_date = new Date(this.parmValue.start_date).valueOf();
      let end_date = new Date(this.parmValue.end_date).valueOf();
      let flag = end_date - start_date > 30 * 24 * 60 * 60 * 1000;
      if(this.parmValue.start_date != "" && this.parmValue.end_date != ""){
        if(flag){
          this.$message.warning("导出文件的时间区间不能超过30天")
          return;
        }
      }else{
        this.$message.warning("请选择导出文件的时间区间")
        return;
      }
      let model = JSON.parse(JSON.stringify(this.parmValue))
      // model.is_export = 1;
      if (!this.loading) {
        this.loading = true;
        //代表发送端(客户端)希望接受的数据类型
        let httpType = `aplication/zip`;
        axios({
          method: "post",
          url: this.fileUrl + "admin/reportorderreturnlist",
          //我需要让他返回的格式为blod
          responseType: "blob",
          data: model,
          headers: {
            // 'Content-Type': 'multipart/form-data',
            // Accept: "application/vnd.ms-excel"
            //Accept代表发送端(客户端)希望接受的数据类型
            Accept: httpType,
          },
        })
          .then((res) => {
            // console.log(res)
            // console.log(this.fileUrl)
            // return;
            if (res && res.status == 200 && res.data) {
              let url = window.URL.createObjectURL(
                new Blob([res.data], {
                  // type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
                  type: httpType
                })
              );
              //创建隐藏的a标签
              let link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              //设置导出文件的名字
              let excelName = "售后明细报表.zip";
              link.setAttribute("download", excelName);
              document.body.appendChild(link);
              //模拟点击事件
              link.click();
              //导出成功后删除这个标签并释放blob对象
              link.remove();
              window.URL.revokeObjectURL(url); //释放掉blob对象
              this.$message.success(`导出成功!`);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            } else {
              this.$message.error(res.data.message);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            }
          })
          .catch((error) => {
            console.log(error);
            this.loading = false;
          });
      }
    },

ok差不多的就到这里了、兄弟们再会!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值