1、需求:页面中点击下载excel文件

2、实现代码a(后端未开启token验证可用)

1
2
3
4
5
6
7
// mian.js文件中
import axios from 'axios'
Vue.prototype.$http = axios
axios.interceptors.request.use(function (config) {
  config.headers.Authorization = localStorage.getItem('token')
  return config
})
1
2
3
4
5
6
7
// 下载页面
download () {
    this.$http.get('xxx url请求地址')
        .then(res => {
        window.location.href = res.config.url
    })
}

存在问题:当后端开启token验证后,界面会提示

window.location.href 就是一个链接跳转,它无法传token

1
2
3
4
{
    resultcode: "-3",
    resultmessage: "token验证不通过,XXX"
}

3、实现代码b(兼容IE10、11)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 下载页面(this.$message为element-UI提示信息)
download () {
    this.pathUrl = 'xxx url请求地址'
    this.$http({
        method: 'get',
        url: this.pathUrl,
        responseType: 'blob'
    }).then((res) => {
        if (res) {
            if ('msSaveOrOpenBlob' in navigator) {
                // Microsoft Edge and Microsoft Internet Explorer 10-11
                window.navigator.msSaveOrOpenBlob(res.data, '文件名称' + new Date().getTime() + '.xls')
                this.$message({
                    message: '导出成功',
                    type: 'success'
                })
            } else {
                // standard code for Google Chrome, Mozilla Firefox etc
                let url = window.URL.createObjectURL(res.data)
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', '文件名称' + new Date().getTime() + '.xls')
                document.body.appendChild(link)
                link.click()
                this.$message({
                    message: '导出成功',
                    type: 'success'
                })
            }
        } else {
            this.$message({
                message: '导出失败',
                type: 'error'
            })
        }
    })
}