前端下载数据流文件

  • 接口配置
export function exportEmployeeList (data) {
 return post(`${baseUrl}staff/excel`, data, {
   headers: {
     'Content-Type': 'application/json'
   },
   responseType: 'blob'
 })
}
  • 转化文件
exportEmployeeList({
  mainDepartmentIds: mainDepartmentId,
  keyWords: this.searchData.name
}).then(res => {
  const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  downloadElement.download = decodeURI('员工列表') // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
})
  • 设置文件名-从请求头中获取
// 1. 以vue为例,接口请求由axios封装需要在拦截器返回请求头
// 2. 根据返回请求头数据配置数据
...
const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
const contentDisposition = res.headers['content-disposition'].split('=')[1] || ''
const iconv = require('iconv-lite') // 设置转码工具
iconv.skipDecodeWarning = true // 忽略警告
const fileName = iconv.decode(contentDisposition, 'utf-8') // 对应后台返回类型进行转码
downloadElement.href = href
downloadElement.download = decodeURI(fileName.split('.')[0]) // 下载后文件名
...
  • 总结
  1. 后端返回的数据流时,前端和后端约定好返回的数据格式
    在这里插入图片描述
  2. 前端同步设置responseType为blob
  3. 转换blob时配置type值如下即可
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
  4. 文件名编码格式需同后台返回一致
    在这里插入图片描述

浏览器兼容问题记录-safari浏览器兼容

// 直接使用window.open()方法safari不支持下载csv格式文件
// safari浏览器打开.csv格式文件时会默认打开文件,而不是触发文件下载,所以在处理时应该把数据流修改为blob格式,具体处理如下:
const blob = new Blob([data], { type: 'text/csv' });
const url = URL.createObjectURL(blob);

const link = document.createElement('a');
link.href = url;
link.download = 'my_file.csv';
link.click();

URL.revokeObjectURL(url);

// 如果是文件下载地址,则应该下载文件内容
fetch(data?.url)
.then(response => response.blob())
.then((blob) => {
  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.href = url;
  const fileNameList = data?.url?.split('?')[0].split('/');
  link.download = decodeURIComponent(fileNameList[fileNameList.length - 1]);
  link.click();

  URL.revokeObjectURL(url);
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值