前端vue通用文件导出(axios)

import axios from 'axios'
import qs from 'qs'
function download(url, params, method = 'GET') {
  return new Promise((resolve, reject) => {
    downloadRequest(url, params, method).then(response => {
      if (response.data.type === 'application/octet-stream') {
        const fileName = response.headers['content-disposition'].split('=')[1]
        /* 兼容ie内核,360浏览器的兼容模式 */
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          const blob = new Blob([response.data], { type: 'application/zip' })
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          /* 火狐谷歌的文件下载方式 */
          const blob = new Blob([response.data], { type: 'application/zip' })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a') // 创建a标签
          link.href = url
          link.download = decodeURI(fileName)
          link.click()
          URL.revokeObjectURL(url) // 释放内存
        }
        resolve(response)
      } else {
        const reader = new FileReader()
        reader.onload = function(event) {
          const msg = JSON.parse(reader.result).data
          this.$message.error(msg) // 显示错误信息
        }
        reader.readAsText(response.data)
        resolve(response)
      }
    }).catch(error => {
      this.$message.error('' + error)
      reject(error)
    })
  })
}
function downloadRequest(url, params, method) {
  return new Promise((resolve, reject) => {
    if (method === 'GET') {
      axios({
        method,
        url,
        params,
        paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'brackets' }) },
        responseType: 'blob'
      }).then(response => { resolve(response) }).catch(error => { reject(error) })
    } else {
      axios({
        method,
        url,
        data: params,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // 将传给后台的数据转换成FormData
        transformRequest: [function(data) { // 格式转换
          data = qs.stringify(data)
          return data
        }],
        responseType: 'blob'
      }).then(response => { resolve(response) }).catch(error => { reject(error) })
    }
  })
}

你可能感兴趣的:(JavaScript/ES6,个人笔记/备忘录,javascript)