分享一个在工作中常用到的文件流下载函数,可把后端传过来的文件流转化为excel表格;
downloadExcel (data) {
const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
const fileUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.setAttribute('href', fileUrl)
a.setAttribute('download', 'fileName')
a.click()
}
使用该函数:
//请求后端接口
async exportData() {
const params = {}
const res = await export(params)
this.downloadExcel(res)
}
注意,要在暴露接口的时候加上类型限制
export const exportData = (params) => request({
url: '/test/test',
method: 'get',
params,
responseType: 'blob',
})
这样,就可以正常下载了。