vue中文件下载功能实现

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

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

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

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

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

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

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

// 下载页面(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'
            })
        }
    })
}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值