vue 下载zip文件

 zipAndDownload(downloadName, executorId) {
      let path = baseUrl.auth + `/schedulelog/zipAndDownload?executorId=${executorId}`;
      axios
        .get(path, {
          responseType: 'blob',
          headers: { 'Content-Type': 'application/zip' },
          data: true //get请求设置 Content-Type 不生效 ,加上 data:true  后生效
        })
        .then(res => {
          let data = res.data;
          let _self = this;
          let fileReader = new FileReader();
          fileReader.onload = function () {
            try {
              let jsonData = JSON.parse(this.result); // 说明是普通对象数据,后台转换失败
              console.log(jsonData, '---------------jsonData');
              if (jsonData.success === false) {
                // 接口返回的错误信息
                // alert(jsonData.msg)
                _self.$message.error(jsonData.msg); // 弹出的提示信息
              }
              _self.btnLoading = false;
            } catch (err) {
              // 解析成对象失败,说明是正常的文件流
              const blob = new Blob([res.data], { type: 'application/zip' }); // 如类型为excel,type为:'application/vnd.ms-excel'
              const fileName = res.headers.filename || downloadName;
              const url = window.URL.createObjectURL(blob);
              const link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', fileName);

              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link); // 点击后移除,防止生成很多个隐藏a标签
              _self.btnLoading = false;
            }
          };
          fileReader.readAsText(data); // 注意别落掉此代码,可以将 Blob 或者 File 对象转根据特殊的编码格式转化为内容(字符串形式)
        })
        .catch(err => {
          console.log(err);
          this.$message.error("下载失败")
          this.btnLoading = false;
        });
    },
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐