axios use new FileReader () to download files for error information returned

this.axios ({
          method: "post",
          url: url,
          date: date,
          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); pop-up error msg // return
                }
              } catch (err) {
                let fileName = 'Download file name .xls'
                // compatible 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 ( 'export success')
              }
            }
            r.readAsText(data) // FileReader的API
          })
          .catch(e => {
            let msg = "abnormal network";
            _that.isCanClick = true
            this.$Message.error(msg);
          });
 
 // download file
    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();
    },

Guess you like

Origin www.cnblogs.com/jiajiamiao/p/11607598.html