vue+axios实现文件下载

https://blog.csdn.net/xjf106/article/details/89361311

https://www.cnblogs.com/yulj/p/8494465.html

// 响应拦截器
service.interceptors.response.use(
  /**
   * 通过接口返回码确定返回状态
   * 还可以通过HTTP状态代码来判断请求状态
   */
  response => {
    // 响应数据
    const res = response.data

    // 返回码200:成功
    if (res.code === 200||res.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
      return res
    } else {
      // 返回码401:AdminToken无效
      if (res.code === 401) {
        MessageBox.confirm(res.msg, '提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }).catch(() => {})
      } else {
        Message({
          showClose: true,
          message: res.msg || 'Server error',
          type: 'error',
          duration: 5000
        })
      }
      return Promise.reject(new Error(res.msg || 'Server error'))
    }
  },
  error => {
    // 响应错误
    console.log(error.response)
    const res = error.response.data
    if (res.code === 401) {
      MessageBox.confirm(res.message, '提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }).catch(() => {})
    } else {
      Message({
        showClose: true,
        message: res.message || error.message,
        type: 'error',
        duration: 5000
      })
    }
    return Promise.reject(error)
  }
)
export function download() {
  return request({
    url: '/base/Teacher/download',
    method: 'get',
    responseType: 'blob'
  })
}
    download()
    {
      download().then(response => {
        this.downloadFile(response);
        this.$message.success(response.msg)
      }).catch(function (error) {
        console.log(error);
      });
    },
    // 下载文件
    downloadFile (data) {
      if (!data) {
        return
      }
      let blob = new Blob([data])
      let fileName = '教师导入模板.xlsx'
      if ('download' in document.createElement('a')) { // 不是IE浏览器
        let url = window.URL.createObjectURL(blob)
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
      } else { // IE 10+
        window.navigator.msSaveBlob(blob, fileName)
      }
    }

 

posted @ 2021-05-18 22:34  shiningrise  阅读(467)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css