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

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