多 / 单文件 下载思路 代码 get导出post 导出

多个文件下载

var count = 0;

 var hiddenIFrameID = 'hiddenDownloader' + count++;

ifram  文档标签

var iframe = document.createElement('iframe');----创建一个标签文档的dom节点

        iframe.id = hiddenIFrameID;-----dom节点的id是一个不重复的随机数

        iframe.style.display = 'none';-----dom节点的display  为 none

        document.body.appendChild(iframe);-----新建的dom节点 用appendChild()方法放入bodyDom

iframe.src = process.env.VUE_APP_HTTP_URL +  `/report/stock/file/download?fileId=${id}`;

       新建的dom节点跳转路径是后面一串  配置的环境路径  和后端提供的路径  以及  下载文件 id

  downLoadFilePL(){
        let that = this

        that.dataList.forEach(item => {
            if(item.fileInfoList.length){
            //    item.fileInfoList.forEach(i => {
            //         that.downloadFile('PL',i.id,i)
            //    }) 
            that.downloadFile('PL',item.fileInfoList[0].id,item)
            }
        })
    },
    downloadFile(type,fileID,obj) {
        let id = ''

        if(type == 'PL'){
            id = fileID
        }else{
            if(obj.fileInfoList.length){
                id = obj.fileInfoList[0].id
            }
        }
        var count = 0;
        var hiddenIFrameID = 'hiddenDownloader' + count++;
        var iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        iframe.src = process.env.VUE_APP_HTTP_URL +  `/report/stock/file/download?fileId=${id}`;
   }

一个文件下载

  // 附件下载
    downItem(type,fileID,obj){
        let id = ''
        console.log('111')

        if(type == 'PL'){
            id = fileID
        }else{
            if(obj.fileInfoList.length){
                id = obj.fileInfoList[0].id
            }
        }
        let url = `/report/stock/file/download?fileId=${id}`
        window.location.href = process.env.VUE_APP_HTTP_URL + url;
    },

不管是get请求还是post请求,后端导出接口都是返回文件的二进制流,这是毋庸置疑的,当查询参数较多的时候,建议使用post,当查询参数较少,使用get请求更好。但是对于前端而言,post请求和get请求会对他们影响较多,get请求的话,前端直接location.href=/url?param=${encodeURI(JSON.stringify(queryObj))} 就可以达到下载文件的效果,但是post请求的话,前端需要写的代码可能要多点,
--------------------get请求

GET请求方式是比较简单的,简单的处理前端只需要通过一个a标签就能实现导出或下载。

但是使用GET请求的需要考虑:

检索条件多不多,其次就是如果检索条件拼接在请求URL上会不会超过请求URL的最大长度。如果请求URL的长度超过浏览器的限制长度,浏览器将会将请求自动截断。

GET请求适用于导出所有数据或者是有个把检索条件并且检索条件长度不是特别长的。总之简单导出使用GET请求还是很香的

-----------------------post请求

POST请求的方式做导出比较的麻烦,需要前后端配合来使用,为了确保更好的用户体验(在用户点击导出或下载后,可以看到文件的下载进度),通过流的方式来实现导出或下载。

后端将处理好的数据存储在Excel表格中,读取Excel表格,以流的方式响应给前端;

前端通过Blob类型接收,通过window.URL.createObjectURL()创建源路径,使用document文档对象创建一个a标签;为a标签添加href属性和值(值就是源路径),为a标签设置download属性和值(值就是被下载的文件名),将指定a标签节点加到document.body的末尾,最后为a标签设置一个自触发的点击事件。

POST请求最适用于检索条件多的场景

举例--导出接口 封装

// 导出接口封装
    exportFun (url, loading, filename) {
      this.$httpGet(url).then(res1 => {
        console.log('res1',res1)
        if(res1.status === 200 && res1.data && res1.data.actionResult != 0){
          this.$httpGet(url, null, null, { responseType: 'blob' }).then((res) => {
            console.log('res',res)
            if (res.status === 200 && res.data && res.data.actionResult != 0) {
              let url = window.URL.createObjectURL(new Blob([res.data], { type: "application/vnd.ms-excel;charset=UTF-8" }));  // new Blob([data])用来创建URL的file对象或者blob对象
              // let filename = '';
              if (res.headers['content-disposition']) {
                filename = res.headers['content-disposition'].split(';')[1].split('=')[1];
              } else {
                filename = `${filename}.xls`
              }
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.download = decodeURI(filename);
              document.body.appendChild(link);
              link.click();
              setTimeout(() => {
                if(loading != ""){
                  this[loading] = false;
                }
                this.$Message.success({
                  content: '导出成功!',
                  duration: 5
                });
              }, 3000)
            } 
          })
        } else if (res1.data.actionResult == 0) {
          this[loading] = false;
          this.$Message.warning({
            content: res1.data.data,
            duration: 5
          });
        }
      })
      .catch((error) => {
        if (error.response) {
          if (error.response.status == 403) {
            this.$Message.error({
              content: '没有权限!',
              duration: 4
            })
          } else {
            this.$Message.error({
              content: '服务器错误:' + error.response.message,
              duration: 5
            });
          }
        } else {
          this.$Message.error({
            content: '服务器错误:' + error,
            duration: 5
          });
        }
      })
    },

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值