前端 文件流下载blob

1.axios请求携带 responseType: 'blob'

export function getCreateReport(id) {
  return request({
    url: `${apiPrefix}/bus/proposal/evaluation/${id}`,
    method: 'Get',
    responseType: 'blob'
  })
}

2.编写下载方法

// blob文件下载
export function downBlobFile(fileName, fileBlob) {
  const link = document.createElement('a')
  try {
// let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'}); //如果后台返回的不是blob对象类型,先定义成blob对象格式,type格式根据返回文件不同修改 const blob = fileBlob const _fileName = fileName // 拆解获取文件名,如果后端没返回文件格式,则需要自己拼接文件后缀 link.style.display = 'none' // 兼容浏览器 const url = window.URL || window.webkitURL || window.moxURL link.href = url.createObjectURL(blob) // 如果没设置axios请求reponseType为‘blob’的话,则参数应为new Blob(文件流),否则报错 link.download = _fileName // 下载的文件名称 link.click() window.URL.revokeObjectURL(url) // #URL.revokeObjectURL()方法会释放一个通过URL.createObjectURL()创建的对象URL. 当你要已经用过了这个对象URL,然后要让浏览器知道这个URL已经不再需要指向对应的文件的时候,就需要调用这个方法. } catch (error) { console.error(error.message) } }

3.调用函数

      const result = await getCreateReport(id)
      downBlobFile(`商标申请评估报告`, result.data)

posted on 2023-09-05 16:03  ChoZ  阅读(190)  评论(0编辑  收藏  举报

导航