vue 后端传文件流前端解析并下载

注:很多小伙伴可能会出现,下载后乱码情况,因为后端传的文件流。

前端请求的时候,在请求体上需要添加申明:

export function downloadExcelTemplate() {
    return request({
      url: 'api/xxx/xxxx',
      method: 'post',
      responseType: 'blob', // 申明为文件流
    })
  }

 

解决方法:

       let url = window.URL.createObjectURL(new Blob([res]))
       let a = document.createElement('a')
       a.style.display = 'none'
       a.href = url
       let title = 'xxxx.xlsx'
       a.setAttribute('download',title)
       document.body.appendChild(a)
       a.click() //执行下载
       window.URL.revokeObjectURL(a.href) // 清除url
       document.body.removeChild(a)//移除dom

 

posted @ 2023-05-09 09:58  Yimuqiao  阅读(191)  评论(0)    收藏  举报