天天看點

axios responseType: ‘blob‘下載下傳檔案,失敗時轉換成json

axios配置responseType: 'blob'時,接口傳回成功的資料是正常的檔案流,傳回失敗的時候也會以檔案流的形式下載下傳到本地,但是是一個損壞的檔案。

通過觀察發現:有效的情況下傳回的type是application/octet-stream,而失敗的時候type是application/josn,那我們就根據這個條件對結果進行處理,對失敗的結果轉換成json,在頁面給出錯誤提示。

axios responseType: ‘blob‘下載下傳檔案,失敗時轉換成json

處理代碼如下:

正常的type為application/octet-stream時,就執行下載下傳到本地的操作,否則頁面提示 

if (response.data.type === 'application/octet-stream') {
          const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a') // 建立a标簽
          link.href = url
          link.click()
          URL.revokeObjectURL(url) // 釋放記憶體
        } else {
          // 将blob檔案流轉換成json
          const reader = new FileReader()
          reader.onload = function (event) {
            const message = JSON.parse(reader.result).data
            _this.$errorMsg(message) // 将錯誤資訊顯示出來
          }
          reader.readAsText(response.data)
        }
           

 給出下載下傳的完成代碼:

axios({
        method: 'GET',
        url: '/logistics/orderExcel',
        params, // 參數
        // 參數格式轉換,否則會報跨域問題!!
        paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'brackets' }) },
        responseType: 'blob'
      }).then(response => {
        if (response.data.type === 'application/octet-stream') {
          const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a') // 建立a标簽
          link.href = url
          link.click()
          URL.revokeObjectURL(url) // 釋放記憶體
        } else {
          // 将blob檔案流轉換成json
          const reader = new FileReader()
          reader.onload = function (event) {
            const message = JSON.parse(reader.result).data
            _this.$errorMsg(message) // 将錯誤資訊顯示出來
          }
          reader.readAsText(response.data)
        }
      }).catch(error => {
        _this.$errorMsg('' + error)
      })