導出文件,responseType設置爲'arraybuffer',如果導出出錯,後臺返回錯誤信息應該怎麼辦?

1、正常導出的情況:(使用axios發送請求)後端返回二進制文件流

api:

//導出api

export function download(className,data){

return request({

url:'/api/'+className+'/export',

methods:'get',

params:data,

responseType:'arraybuffer',

})

}

// 調用api

this.$api.download(className,{name:nameCN,...this.searchForm}).then(res=>{

const data = new Blob([res],{type:'application/vnd.ms-excel'})

const url = URL.createObjectURL(data)

const a = document.createElement('a')

a.href = url

a.download = 'table.xls'

a.click()

URL.revokeObjectURL(url)

})

2、後來數據量過多導出出錯,和後端約定,如果數據量過多則後端返回錯誤信息:

{
message: "數據量太大,建議導出數據不要超過6萬以上"
retcode: "111111"
style: "PLAIN"
timestamp: 1570605714954
uri: "/api/zyBrfymxk/export"
}

由於請求的時候設置了responseType:'arraybuffer',返回的是數據流,要取得json信息需要進行轉換:

let enc = new TextDecoder('utf-8')
let data = JSON.parse(enc.decode(new Uint8Array(res.data)))

// 調用api 改成:

this.$api.downloadXlsx(className,{name:nameCN,...this.searchForm}).then(res=>{
          try {
                let enc = new TextDecoder('utf-8')
                let data = JSON.parse(enc.decode(new Uint8Array(res.data)))
                this.$message({
                  message: data.message,
                  type: 'warning'
                });
                this.downloading = false
          } catch (error) {
                this.downloading = false
                const data = new Blob([res.data],{type:'application/vnd.ms-excel'})
                const url = URL.createObjectURL(data)
                const a = document.createElement('a')
                a.href = url
                a.download = nameCN+'.xlsx';
                a.click()
                URL.revokeObjectURL(url)
          }
        })

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章