思路大概是这样的
- 文件流
- Blob类型
- URL
- 创建a标签
- 指定href为URL
- 设置download属性来指定文件名
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12
| export const downloadFile = (_blob: Blob, fileName: string) => { const blob = new Blob([_blob], { type: 'application/vnd.ms-excel' }) const a = document.createElement('a') a.style.display = 'none' const href = window.URL.createObjectURL(blob) a.href = href a.download = fileName document.body.append(a) a.click() document.body.removeChild(a) window.URL.revokeObjectURL(href) }
|
常用的excel对应得mine-type类型:
"application/vnd.ms-excel"
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
重点:在response中加上responseType: 'blob'。