关于vue.js:前端将后端返回的文件流转为excel并下载

3次阅读

共计 1087 个字符,预计需要花费 3 分钟才能阅读完成。

在日常开发中,咱们可能会遇到导出 excel 的状况,而后端此时给咱们返回的是一个文件流,须要前端将文件流转为 url 地址进行下载。

能够将这个办法封装成一个工具类,不便其余中央调用,我这里放到了 utils.js 外面

import axios from 'axios'
import Vue form 'vue'

/**
 * 依据后端返回的文件流转为 excel 导出
 * @param {Object} data
 */
export function exportExcelMethod(data) {
  axios({
    method: data.method,
    url: `${data.url}${data.params ? '?' + data.params : ''}`,
    responseType: 'blob',
    headers: {token: data.token},
    timeout: 8000,
    data: data.data
  })
    .then((res) => {const link = document.createElement('a')
      const 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 = data.fileName // 下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      Vue.prototype.$message.success('导出胜利!')
    })
    .catch((error) => {Vue.prototype.$message.error('参数谬误!')
    })
}
<el-button type="primary" plain size="small" @click="exportLog"> 导出 </el-button>
import {exportExcelMethod} from '@/utils'

exportLog() {
    const url = this.baseUrl
    const data = this.data
    const myObj = {
      method: 'post',
      url: url,
      fileName: 'xxx 日志',
      token: this.token,
      data: {data}
    }
    exportExcelMethod(myObj)
  }
正文完
 0