post导出excel

前言

在做 excel 导出时,经常需要导出选中的行,然选中的行需要将 id 传给后台,如果使用 get 方式导出,在浏览器地址栏能导出的行数是有限。此时,就需要用到 POST 方式导出了。

环境

  • axios
  • element-ui
  • vue 2.5.2

POST导出

request.js

import axios from 'axios'
import { Message } from 'element-ui'
/**
 * 请求函数
 */
const request = (url, data = {}, method = 'post', options = {}) => {
  return axios.request({
    url,
    data,
    method,
    ...options
  })
}

/**
 * 从服务器下载excel
 */
const postDownload = (url, data) => {
  const defaultOptions = {
    responseType: 'arraybuffer'
  }
  request(url, data, 'post', defaultOptions).then(res => {
    const filename = decodeURI(res.headers['content-disposition'].split('filename=')[1])
    if ('download' in document.createElement('a')) {
      downloadFile(res.data, filename)
    } else {
      Message.error('浏览器不支持')
    }
  })
}

/**
 * blob下载(兼容IE)
 * @param {String} content 文件内容
 * @param {String} filename 文件名
 */
const downloadFile = (content, filename) => {
  const blob = new Blob([content])
  // IE
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename)
  } else {
    imatateDownloadByA(window.URL.createObjectURL(blob), filename)
  }
}

/**
 * 通过a标签模拟下载
 * @param {String} href
 * @param {String} filename
 */
const imatateDownloadByA = (href, filename) => {
  const a = document.createElement('a')
  a.download = filename
  a.style.display = 'none'
  a.href = href
  document.body.appendChild(a)
  a.click()
  a.remove()
  // 释放掉blob对象
  window.URL.revokeObjectURL(href)
}

测试下载

postDownload('http://locahost:3000/excel/export')

参考

https://www.jianshu.com/p/a81c68c15fbd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章