• 下载二进制文件


    如果后台返回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
  • 相关阅读:
    (转)【web前端培训之前后端的配合(中)】继续昨日的故事
    ural(Timus) 1136. Parliament
    scau Josephus Problem
    ACMICPC Live Archive 6204 Poker End Games
    uva 10391 Compound Words
    ACMICPC Live Archive 3222 Joke with Turtles
    uva 10132 File Fragmentation
    uva 270 Lining Up
    【转】各种字符串哈希函数比较
    uva 10905 Children's Game
  • 原文地址:https://www.cnblogs.com/zhangrenjie/p/14137738.html
Copyright © 2020-2023  润新知