首先要在请求中 让返回的数据为blob 本人这里使用的请求库为axios 写法如下
export const educeListExcel = (data) => {
return request({
method: 'post',
url: '/api/DbSet/AllListExcel',
data,
// 这里设置请求返回数据为blob
responseType: 'blob',
})
}
新建一个 download.js文件 代码如下
export default function download(response, fileName) {
// 用户环境信息
const uA = window.navigator.userAgent
// 判断是不是ie浏览器 不考虑兼容可以删除
const isIE =
/msie\s|trident\/|edge\//i.test(uA) &&
!!(
'uniqueID' in document ||
'documentMode' in document ||
'ActiveXObject' in window ||
'MSInputMethodContext' in window
)
//
if (!fileName) {
fileName = response.headers
.get('Content-Disposition')
.split(';')[1]
.split("filename*=UTF-8''")[1]
const fileNameUnicode = response.headers
.get('Content-Disposition')
.split('filename*=')[1]
if (fileNameUnicode) {
// 当存在 filename* 时,取filename* 并进行解码(为了解决中文乱码问题)
fileName = decodeURIComponent(fileNameUnicode.split("''")[1])
}
}
if (isIE) {
navigator.msSaveBlob(response, fileName)
// 可能会出现有body的情况
// navigator.msSaveBlob(response.body, fileName)
} else {
// 响应文件 文件流做为路径
const objectUrl = window.URL.createObjectURL(response)
// 可能会出现有body的情况
// const objectUrl = window.URL.createObjectURL(response.body)
// 创建a标签 达到下载效果
const a = document.createElement('a')
a.addEventListener('click', () => {
a.download = fileName
a.href = objectUrl
})
const e = document.createEvent('MouseEvents')
e.initEvent('click', false, false)
a.dispatchEvent(e)
}
}
在请求文件中 引入
import download from '../../utils/download'
然后使用
onClick={async () => {
const { data: res } = await educeListExcel({
pageIndex: 1,
pageSize: 20,
conditions: []
})
// res 请求数据 第二个参数为自定义文件名
download(res, 'test.xlsx')
}}
如此万事大吉