前端下载文件(使用后端传的文件名)

使用场景:后端response传的是文件流

// 文件下载 - (不传文件名则取后端定义的文件名)
export const downloadFileNew = (url, fileName) => {
  const xhr = new XMLHttpRequest()
  xhr.open('get', url)
  xhr.responseType = 'blob'
  xhr.setRequestHeader('Authorization', getToken()) // 权限验证,视情况修改
  xhr.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      const name =
        fileName ||
        xhr.getResponseHeader('Content-Disposition').split('filename=')[1]

      // 支持IE浏览器
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(this.response, name)
        return
      }
      const href = window.URL.createObjectURL(this.response)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = href
      link.setAttribute('download', name)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
  xhr.send()
}

异常情况处理:

如果xhr.getResponseHeader('Content-Disposition')出错,出现获取不到响应头的情况,则可能是后端没有设置该值的获取权限。

在后端加上该值的权限即可:

context.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

你可能感兴趣的:(前端下载文件(使用后端传的文件名))