下载二进制文件

如果后台返回url,则使用window.open()

如果后台接口返回的是二进制流

axios({
  method: 'post',
  url: '/export',
  responseType: 'arraybuffer',
})
.then(res => {
  // 假设 data 是返回来的二进制数据
  const data = res.data
  const url = window.URL.createObjectURL(new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', 'excel.xlsx')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
})

 

封装:

// 导出excel
import { Loading } from "element-ui";
const exportExcel = ({url, type='post', params={}, excelName='excel'}) => {
  var loadingInstance = Loading.service(
    Loading.service({
      background: "rgba(0,0,0,0.5)"
    })
  )
  baseAxios[type](url, params, {responseType: 'blob'}).then(res => {
    const link = document.createElement('a')
    let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'})
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    // link.download = res.headers['content-disposition'] //下载后文件名
    link.download = `${excelName}_${new Date().getTime()}`  //下载的文件名
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    loadingInstance.close();
  }).catch(() => {
    loadingInstance.close();
  })
}
export default exportExcel

 

posted @ 2020-12-15 11:57  异地大光码  阅读(161)  评论(0编辑  收藏  举报