フロントエンド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) })
    }
  })
}