在文件流下载过程中,如果需要动态修改header 鉴权,或者下载之后改变文件名称,需要用到Blob 对象

import axios from 'axios'

function exportExcel(headers) {
  return axios({
    url: process.env.VUE_APP_BASE_API + '/wms/smart/usage/template',
    method: 'get',
    responseType: 'blob',
    headers: headers
  })
}    

handleExport() {
      const headers = {}
      headers[getTokenName()] = getToken()
      API.exportExcel(headers).then(res => {
        if (res.data.type === 'application/json') {
          this.$message({
            type: 'error',
            message: '下载失败,文件不存在或权限不足'
          })
        } else {
          const blob = new Blob([res.data])
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, '文件名.xlsx')
          } else {
            const link = document.createElement('a')
            const evt = document.createEvent('HTMLEvents')
            evt.initEvent('click', false, false)
            link.href = URL.createObjectURL(blob)
            link.download = '文件名.xlsx'
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
            window.URL.revokeObjectURL(link.href)
          }
        }
      })
    }

标签: none

添加新评论