导出文件,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)
          }
        })

猜你喜欢

转载自blog.csdn.net/zhongmei121/article/details/94430203
今日推荐