Excel文件导出(post请求后端返回excel文件流)

965 阅读1分钟

前提:管理系统中,有一些数据需要导出文件,点击之后后台请求返回excel文件流,但是返回数据response是乱码的

image.png

image.png

  1. 用的是axios请求后台的,首先设置responseType: 'blob'

知识补充responseType 表示服务器响应的数据类型,可以是 arraybuffer、blob、document、json、text、stream详情可以看axios配置

  1. 针对后台返回的response做处理,,打印了一下返回的response如下图

image.png

完整代码:

// 如何使用的例子
this.download('/xxxxxURL',{fileID:'000000'}, (res)=>{
    alert("导出成功")
})
                        
                  
download(url, param, _success, _failure) {
    axios({
        method: "POST",
        url: url,
        data:param,
        responseType: 'blob' //返回是个文件 重要的
    }).then(response => {
        console.log('response', response);
        // 需要利用downloadFile方法对response进行操作
        this.downloadFile(response, () => {
            console.log('下载完成');
            _success();
        }) //then直接下载,方法在下边
    }).catch((error, _t) => {
        _failure();
    })
}

// 下载文件(最重要的,对于返回的response进行操作)
downloadFile(res, _call) {
    let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });//type是文件类,详情可以参阅blob文件类型
    // for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob,'下载的文件的名字');
    }else{
        // for Non-IE (chrome, firefox etc.)
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob)
        // 创建a标签,用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        let filename = decodeURI(res.headers['content-disposition'].split('=')[1]);
        tempLink.setAttribute('download', filename);
        // 兼容:某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
    }
    _call();
}