axios 利用new FileReader() 下載文件獲取返回的錯誤信息


this.axios({
          method: "post",
          url: url,
          data: data,
          responseType: "blob" 
        })
          .then(res => {
            const data = res.data
            let r = new FileReader()
            r.onload = function () {
              try {
                let resData = JSON.parse(this.result)
                console.log(resData)
                if (resData && resData['code'] && resData['code'] != '1000') {
                 alert(resData.msg);//彈出返回的錯誤msg
                }
              } catch (err) {
                let fileName = '下載文件名.xls'
                // 兼容ie11
                if (window.navigator.msSaveOrOpenBlob) {
                  try {
                    const blobObject = new Blob([data])
                    window.navigator.msSaveOrOpenBlob(blobObject, fileName)
                  } catch (e) {
                    console.log(e)
                  }
                  return
                }
               this.download(data, fileName)
                alert('導出成功')
              }
            }
            r.readAsText(data) // FileReader的API
          })
          .catch(e => {
            let msg = "網絡異常";
            _that.isCanClick = true
            this.$Message.error(msg);
          });
 
 // 下載文件
    download(data, name) {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", name);
      document.body.appendChild(link);
      link.click();
    },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM