最近在尝试eggjs,实现下载功能的时候遇到的小问题,下载下来的文件无法打开,大佬们帮忙看下是哪一步出现的问题
//前端请求
axios({
method: 'post',
url: 'http://127.0.0.1:7001/download',
data: {},
responseTyp: 'blob',
}).then((res) =>{
if(res) {
let url = window.URL.createObjectURL(new Blob([res]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', `test.xlsx`)
document.body.appendChild(link)
link.click()
}
})
//服务端处理
async download() {
const filePath = path.resolve(this.app.config.static.dir, 'test.xlsx');
this.ctx.attachment('test.xlsx');
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = fs.createReadStream(filePath);
}
前阵子遇到的解决方案是 把返回的res.toBlob()一下,就可以了