React下载后端返回文件流形式的Excel文件(blob)

2,498 阅读1分钟

Java配置代码

前端代码片段(我是封装了一个方法)
downloadExcel 文件

/*res是请求后返回的文件流,name是传入的文件名*/
export const downloadExcel = (res,name) => {
  const blob = new Blob([res],{type: 'application/vnd.ms-excel'})
  const fileName = `${name}.xlsx`
  if ('download' in document.createElement('a')) {
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  } else {
    navigator.msSaveBlob(blob, fileName)
  }
}

models中使用


import { downloadExcel } from '@/utils/downloadExcel'

*export LotteryFile({ payload }, { put, call }) {
    const res = yield call(api.exportLotteryFile, payload)
    downloadExcel(res, '抽奖活动明细')
}