axios获取后端返回字节流

responseType: ‘blob’。首先将这个responseType改为”blob“。即将返回值视为二进制

this.$http({
    
    
    url: this.$http.adornUrl("/getCert"),
    method: "post",
    data: this.certForm,
    responseType: 'blob'
})

将返回值res.data作为flow

创建一个Blob对象,通过该对象创建一个ObjectURL。

创建一个不可见的Html元素,将blobURL赋给该元素,然后模拟点击。

const blob = new Blob([flow])
const blobUrl = window.URL.createObjectURL(blob)

const a = document.createElement('a')
a.style.display = 'none'
var nowDate = new Date();
let date = nowDate.getFullYear()+'-'+(nowDate.getMonth() + 1)+'-'+nowDate.getDate()
// 自定义下载的文件名
a.download = this.certForm.username+this.certForm.org+date+'证书列表.xlsx' 
a.href = blobUrl
a.click()

完整的代码为

 this.$http({
    
    
        url: this.$http.adornUrl("/getCert"),
        method: "post",
        data: this.certForm,
        responseType: 'blob'
    }).then((res)=>{
    
    
        console.log(res)
        this.loading = false
        //返回的res是后端真正返回的res.data
        this.downloadFn(res.data)
        // flow为接口返回的文件流]
    }).catch((e)=>{
    
    `在这里插入代码片`
        this.$message({
    
    
            type: 'error',
            message: e
        });
        this.loading = false
    })
},
downloadFn(flow = null) {
    
    
    if (!flow) return
    const blob = new Blob([flow])
    const blobUrl = window.URL.createObjectURL(blob)

    const a = document.createElement('a')
    a.style.display = 'none'
    var nowDate = new Date();
    let date = nowDate.getFullYear()+'-'+(nowDate.getMonth() + 1)+'-'+nowDate.getDate()
    a.download = this.certForm.username+this.certForm.org+date+'证书列表.xlsx' // 自定义下载的文件名
    a.href = blobUrl
    a.click()
}

猜你喜欢

转载自blog.csdn.net/weixin_44225096/article/details/125322619