vue项目中如何实现以blob形式导出文件

  介绍

这篇文章将为大家详细讲解有关vue项目中如何实现以blob形式导出文件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

<强> 1,首先要确定服务器返回的数据类型。

在请求头中加入:配置。responseType=& # 39;团# 39;

有时候,不是所有接口都需要该类型,则可以对接口做一个判定:

//请求拦截器
  service.interceptors.request.use (
  配置=比;{//根据接口判定
  如果(配置。url===& # 39;/设置/exportData& # 39;||
  config.url.indexOf(& # 39;出口# 39;)比;1 | |
  config.url.indexOf(& # 39;出口# 39;)比;1){
  配置。responseType=& # 39;团# 39;//服务请求类型
  }
  如果(getToken ()) {
  config.headers [& # 39; access_token& # 39;]=getToken ()
  }
  返回配置
  },
  错误=比;{//请求错误做些什么//console.log(错误)//调试
  Promise.reject(错误)
  }
  )

<强> 2,接口请求获取后端返回的文件流

//导出>//使用iframe框架下载文件——以excel为例,可修改类型与文件名选择文件类型
  导出功能downloadUrl (res,名称){
  const blob=new blob ((res),{类型:& # 39;应用程序/vnd.ms-excel& # 39;})//构造一个blob对象来处理数据
  const文件名=名称+ & # 39;.xlsx& # 39;//导出文件名
  const elink=document.createElement(& # 39;一个# 39;)//创建一个标签
  elink。下载=文件名//标签添加属性
  elink.style。=& # 39;显示没有# 39;
  elink。href=https://www.yisu.com/zixun/URL.createObjectURL (blob)
  document.body.appendChild (elink)
  elink.click()//执行下载
  URL.revokeObjectURL (elink.href)//释放URL对象
  document.body.removeChild (elink)//释放标签
  }

<强> 4,在ie浏览器中存在兼容性问题,对downloadUrl做一些调整

//使用iframe框架下载文件——兼容性考虑
  导出功能downloadUrl (res,名称){
  const blob=new blob ((res),{类型:& # 39;应用程序/vnd.ms-excel& # 39;})//即
  如果窗口。导航器,,window.navigator.msSaveOrOpenBlob) {
  const文件名=名称+ & # 39;.xlsx& # 39;
  window.navigator。文件名msSaveOrOpenBlob (blob)
  其他}{//非ie (chrome, firefox等)。
  const文件名=名称+ & # 39;.xlsx& # 39;
  const elink=document.createElement(& # 39;一个# 39;)
  elink。下载=文件名
  elink.style。=& # 39;显示没有# 39;
  elink。href=https://www.yisu.com/zixun/URL.createObjectURL (blob)
  document.body.appendChild (elink)
  elink.click ()
  URL.revokeObjectURL (elink.href)
  document.body.removeChild (elink)
  }
  }

至此,以文件流的形式导出文件的一种方式便已经实现。

<强> vue中使用文件流进行下载(Blob),不打开一个新页面下载

我就废话不多说了,大家还是直接看代码吧~

导出功能下载(url参数,文件名){
  
  Message.warning(& # 39;导出数据中& # 39;)
  axios返回。get (url, {
  参数:参数,
  responseType: & # 39; arraybuffer& # 39;
  })((r)=比;{
  
  const内容=r.data
  const blob=new blob([内容]{类型:& # 39;应用程序/vnd.ms-excel& # 39;})
  如果(& # 39;下载# 39;在document.createElement(& # 39;一个# 39;)){
  const elink=document.createElement(& # 39;一个# 39;)
  elink。下载=文件名
  elink.style。=& # 39;显示没有# 39;
  elink。href=https://www.yisu.com/zixun/URL.createObjectURL (blob)
  document.body.appendChild (elink)
  elink.click ()
  URL.revokeObjectURL (elink.href)
  document.body.removeChild (elink)
  Message.success(“导出成功”)
  
  }
  
  }).catch ((r)=> {
  console.error(右)
  Message.error(“导出失败”)
  
  })
  }

关于vue项目中如何实现以blob形式导出文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。

vue项目中如何实现以blob形式导出文件