解决方案:是在发送ajax请求时设置请求头:  responseType: 'blob'

注意: post请求和get请求设置请求头的位置还不一样,具体如下:
  post方式:
excelApi.js如下
import axios from 'axios'
excelApi.postExportExcel = params => {
  return axios.post('/exportExcel', params, { responseType: 'blob' })
}
具体的请求方法:使用formData
const f = new FormData()
//添加参数
f.append('pageSize', this.query.pageSize)
f.append('pageNo', this.query.pageNo)
f.append('name', this.query.name)
excelApi.postExportExcel(f).then(res => {
  if (res) {
    this.downloadDialogVisible = false
    const fileNames = res.headers['content-disposition']
    // 解码
    const fileName = decodeURIComponent(fileNames.match(/=(.*)$/)[1])
    // 处理返回的文件流
    const content = res.data
    const blob = new Blob([content], { type: 'application/vnd.ms-excel; charset=utf-8' })
    if ('download' in document.createElement('a')) {
      // 非IE下载
      const a = document.createElement('a')
      a.download = fileName
      a.style.display = 'none'
      a.href = URL.createObjectURL(blob)
      document.body.appendChild(a)
      a.click()
      URL.revokeObjectURL(a.href) // 释放URL 对象
      document.body.removeChild(a)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }
})

get方式:
excelApi.getExportExcel= params => {
  return axios.get('/exportExcel', {
    params: params,
    responseType: 'blob'
  })
}
具体的请求方法:get不使用formData
const getParam = {
  'name': this.name,
  'office': this.office
}
excelApi.getExportExcel(getParam).then(res => {
  if (res) {
    this.downloadDialogVisible = false
    const fileNames = res.headers['content-disposition']
    if (fileNames) {
      // 解码
      const fileName = decodeURIComponent(fileNames.match(/=(.*)$/)[1])
      // 处理返回的文件流
      const content = res.data
      const blob = new Blob([content], { type: 'application/octet-stream; charset=utf-8' })
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const a = document.createElement('a')
        a.download = fileName
        a.style.display = 'none'
        a.href = URL.createObjectURL(blob)
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL 对象
        document.body.removeChild(a)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }
  }
})
Logo

前往低代码交流专区

更多推荐