前端下载后端返回的文件流方式的文件

  1. decodeURI 解析 后端返回的 res.headers['content-disposition'] 里面名字(URL编码的)
  2. res.headers['content-disposition'] 这个在 fixfox浏览器 会有一个 *号 比如 filename*=,所以用 split('='),而不用 split('filename='),并跟后端约定好先filename信息放在 res.headers['content-disposition']  最后一个 = 号,然后前端也是取最后一个。
  3. 传参的时候记得要带上{responseType: 'blob'}
exportExcelStream('post', TestService.testApi(this.bodyParams)) // 调用
/**
 * 文件流方式下载
 * @param typeReq {String} 请求方式
 * @param paramsReq {Array} 解构后axios需要的参数列表
 */
function exportExcelStream (typeReq, paramsReq) {
  Ajax.$http[typeReq](...paramsReq, {responseType: 'blob'}).then((res) => {
    const content = res
    const blob = new Blob([content.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
    const fileNameSplit = res.headers['content-disposition'].split('=')
    const fileName = decodeURI(fileNameSplit[fileNameSplit.length - 1]) // 跟后端约定好最后一个值为fileName字段
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放 URL对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
    // if (window.navigator && window.navigator.msSaveOrOpenBlob) { // 也可这么判断IE10+
    //    window.navigator.msSaveOrOpenBlob(new Blob([data]), fileName)
    // }
  }).catch((err) => {
  })
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值