vue跳转url地址下载文件时如何给文件添加header信息(比如:token)

需求背景:在项目中,通过url跳转链接(location.href或者标签)都可以实现文件下载功能,若需要跳转url时,请求此url接口,目的携带token等请求头信息,则无法通过href等跳转下载,下文主要解决次情况。

vue跳转url地址下载文件时如何给文件添加header信息(比如:token)_第1张图片

1、通过href跳转下载:

   async exportForm() {
      let url =
        process.env.VUE_APP_BASE_API +
        '/api/compare/xxx/xxx/xx/xx?参数信息
      location.href = url
    },

2、携带token请求接口,下载文件

    async exportForm() {
      const res = await exportList()     //请求url接口
      const dowmName=res.headers['content-type'].split('.')[0]   //获取下载文件名称(在请求头中)
    const url = window.URL.createObjectURL(new Blob([res]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute(
          'download',
          `${dowmName}.xlsx`
        )
        document.body.appendChild(link)
        link.click()

  },

接口信息(必写:responseType: 'blob'): 

vue跳转url地址下载文件时如何给文件添加header信息(比如:token)_第2张图片 

获取请求头信息:

vue跳转url地址下载文件时如何给文件添加header信息(比如:token)_第3张图片

你可能感兴趣的:(前端)