欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

请求返回文件流格式,实现下载文件功能,前端代码

程序员文章站 2022-03-13 20:23:37
let _this = this var xhr = new XMLHttpRequest(); let link = process.env.VUE_APP_BASE_API+'/gbgl/downloadDoclist' xhr.open('POST', link, true); // 也可用POST方式 xhr.responseType = "blob"; xhr.onload = function () { ......

      let _this = this
      var xhr = new XMLHttpRequest();
      let link = process.env.VUE_APP_BASE_API+'/gbgl/downloadDoclist'
      xhr.open('POST', link, true);    // 也可用POST方式
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (this.status === 200) {
          var blob = this.response;
          let fr = new FileReader()
          fr.readAsText(blob)
          fr.onload = (e)=>{
            let result = fr.result
            try{
              let msg = JSON.parse(result)
              _this.$message.error(msg.message)
            } catch(e){
              if (navigator.msSaveBlob == null) {
                var a = document.createElement('a');
                var headerName = xhr.getResponseHeader("Content-disposition");
                // console.log(headerName)
                var fileName = decodeURIComponent(headerName)
                if(fileName.indexOf('"')!=-1){
                  fileName = fileName ? fileName.split('filename="')[1] : '下载文件'
                  fileName = fileName ? fileName.split('"')[0]:'下载文件';
                } else {
                  fileName = fileName ? fileName.split('filename=')[1] : '下载文件'
                }
                a.download = fileName;
                a.href = URL.createObjectURL(blob);
                document.body.appendChild(a)
                a.click();
                URL.revokeObjectURL(a.href);
                a.remove();
                _this.$message({type:'success',message:'导出成功!'})
              } else {
                  navigator.msSaveBlob(blob, fileName);
              }
            }
          }
        } else {
          _this.$message({type:'error',message:this.statusText})
        }
      };
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
      xhr.setRequestHeader("token", getToken());
      let query = this.$copy(this.dataForm)
      query.degrees = query.degrees.filter(e=>e.degreeIds||e.educationBackgroundIds)
      query.cadres = this.cadres
      xhr.send(this.$http.adornData(query))

 

本文地址:https://blog.csdn.net/RubyLinT/article/details/107379425

相关标签: js vue javascript