下载文件, 需要带cookie校验时

553 阅读1分钟

下载文件, 需要带cookie校验时

 const url = `/download/${data.id}`
      // window.location.href = url  // 直接下载,
      // console.log('url', url)
      axios.get(url, {
        responseType: 'blob', // 或者responseType: 'blob'
        xsrfHeaderName: 'Authorization',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'bearer ' + getToken()
        }
      }).then(res => {
        const blob = new Blob([res.data])
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob) // 创建下载的链接
        link.setAttribute('download', data.name + '.zip') // 给下载后的文件命名
        document.body.appendChild(link)
        link.click() // 点击下载
        document.body.removeChild(link) //  完成移除元素
        window.URL.revokeObjectURL(link.href) // 释放blob对象
      }).catch(err => {
        console.log(err)
      })
      
      ```