前端导出功能

298 阅读1分钟

1、公共方法的封装

/**
 * 文件导出、下载
 */
const exportFile = (url: string, params: any, type = 'post' as string) => {
  const downFilejx = (res: any) => {
    try {
      const blob = new Blob([res.data], { type: 'application/actet-stream;charset=utf-8' }) as any
      const contentDisposition: string = res.headers['content-disposition'] // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
      const patt: RegExp = new RegExp('filename=([^;]+\.[^\.;]+);*')
      const result = patt.exec(contentDisposition) as any
      const filename: string = toDecodeURIComponent(result[1])
      // for IE
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, filename)
      } else {
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = filename // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      }
    } catch (error) {
      console.log('导出文件出错')
    }
  }
  const urlCope = process.env.VUE_APP_URL + url
  if (type === 'post') {
    http.post(urlCope, params, { 'responseType': 'blob' }).then((res: any) => {
      downFilejx(res)
    })
  }
  if (type === 'get') {
    http.get(urlCope, {
      params,
      'responseType': 'blob'
    }).then((res: any) => {
      downFilejx(res)
    })
  }
}

2、axios封装的时候注意层级

image.png

3、后端返回的格式

image.png

4、页面二进制格式

image.png

5、页面二进制格式

const toDecodeURIComponent = (str: any) => {
  return str ? decodeURIComponent(str) : ''
}