axios 获取后端返回的二进制流转excel失败

  • 后端用poi生成excel对象,通过流输出,测试代码:

ServletOutputStream out = response.getOutputStream();

        wb.write(out);
        out.flush();
        out.close();
  • 页面用axios发送请求,根据博客上的说法,也设置了responseType: 'blob'

请求的测试部分:

export function getExcel() {
  return request({
    url: `${BASE_URL}/meta_db/excel`,
    method: 'POST',
    responseType: 'blob'
  })
}
  • 从后台获取的response:

clipboard.png

页面打印的response, response.data 现在是一个字符串

clipboard.png

  • JS 拿到response.data, 生成Blob,生成的xls文件打开全是乱码

测试代码:

 getExcel().then(response => {
                console.log(response);
                console.log(typeof response.data)
                let url = window.URL.createObjectURL(new Blob([response.data], {
                    type: "application/vnd.ms-excel;charset=utf-8"
                }))
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', 'excel.csv')
                document.body.appendChild(link)
                link.click();
            })

结果:

clipboard.png

有人知道这个问题的解决办法吗? 谢谢

阅读 4.4k
1 个回答

都是buffer能出什么问题,如果你能确定你excel文档生成没问题,就是本地系统打开excel出问题。想验证很简单,对比下buffer就行了,比如做个md5

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题