vue二进制下载

封装axios,/api/request

import axios from 'axios'
import store from '@/store'
import Vue from 'vue'
import { Message, MessageBox } from 'element-ui'

import { getToken } from '@/utils/auth'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const $axios = axios.create({
  // 设置超时时间
  timeout: 30000,
  // 基础url,会在请求url中自动添加前置链接
  baseURL: process.env.VUE_APP_BASE_API
})

Vue.prototype.$http = axios // 并发请求
// 在全局请求和响应拦截器中添加请求状态

// 请求拦截器
$axios.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = getToken() // 请求头部添加token
      config.headers.tenantId = store.getters.tenantId
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
$axios.interceptors.response.use(
  response => {
    if (response.headers['content-type'] === 'application/octet-stream') {
      return response
    }
    // if(response.headers['content-type'] ==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
    //   return response
    // }
    if (response.headers['content-type'] !== 'application/json; charset=utf-8') {
      return response
    }
    const res = response.data || res
    if (res.success || res.data || res.result_code === 'SUCCESS') {
      return Promise.resolve(res)
    } else {
      return Promise.reject(res)
    }
  },
  error => {
    let code = ''
    if (error && error.response) {
      code = error.response.status
    }
    if (code === 401) {
      return MessageBox.confirm(
        '登录状态已过期,请重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('LoginOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
        return Promise.reject(new Error('正在为您跳转登录页!'))
      }).catch(() => {
        return Promise.reject(new Error('登录过期,请您重新登录!'))
      })
    } else if (code === 404) {
      Message({
        message: '网络请求不存在!',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (code === 429) {
      return Promise.reject(new Error('访问频繁!'))
    } else if (code === 403) {
      return Promise.reject(new Error('很抱歉,您的访问权限等级不够,联系管理员!'))
    } else {
      return Promise.reject(error || new Error('请求超时'))
    }
  }
)

// Content-Type
// 'application/json; charset=UTF-8'
// 'Content-Type': 'multipart/form-data' 需要在表单中上传文件以二进制流的方式传递数据
// 'application/x-www-form-urlencoded; charset=UTF-8'  以键值对的方式传递参数
// responseType: 'blob'                 接收文件流
export default $axios

引入/api/request,写接口 

import request from './request'
export function exportReport(data) {
  return request({
    method: 'post',
    url: '/api/ExportExcel/Export',
    data,
    responseType: 'blob'
  })
}

下载

导出

// 导出
exportHandle() {
  if (this.isDownloading) return
  this.isDownloading = true
  const params = {
    export_name: 'StockSupplierData',
    ...this.schData
  }
  const fileName = '列表' + getTimeStr()
  exportReport(params).then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, fileName + '.xlsx')
      this.isDownloading = false
    } else {
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      const a = document.createElement('a')
      a.style.display = 'none'
      a.download = fileName + '.xlsx'
      a.href = href
      document.body.appendChild(a) // 修复firefox中无法触发click
      a.click()
      document.body.removeChild(a)
      this.isDownloading = false
    }
  }).catch(err => {
    this.isDownloading = false
    this.$message.error(err.msg || err.message || '导出失败')
  })
}
// getTimeStr是封装的时间戳
export function getTimeStr() {
    let date = new Date()
    let str = '' +
        date.getFullYear() +
        padStart((date.getMonth() + 1)) +
        padStart(date.getDate()) +
        padStart(date.getHours()) +
        padStart(date.getMinutes()) +
        padStart(date.getSeconds())
    return str
}

或者

axios.post('xxx/api/xxx',
  {
    ...params
  },
  {
    responselype: 'blob',
    headers: {
      'Authorization': getToken()
    }
  }
).then(res => {
  console.log('res', res)
}).catch(err => {
  console.log('err', err)
})

vue二进制下载_第1张图片 

 

 

你可能感兴趣的:(vue.js,javascript,前端)