后端下载文件返回base64格式数据转二进制流下载

该代码段展示了如何从后端获取Base64格式的文件内容,然后转换为二进制并触发浏览器下载。它使用`useDownloadByBase64`函数将Base64数据转换为Blob对象,创建一个隐藏的a标签来模拟点击下载,并通过`window.URL.createObjectURL`创建可下载的URL。
摘要由CSDN通过智能技术生成

 import { useDownloadByBase64 } from '@/utils/transform'
const handleDownload = (id: string) => {
  version_download({ id }).then(res => {
    //后端返回base64格式转为二进制下载
    if (res.file) return useDownloadByBase64(res.file, fileName)
    //后端返回完整文件下载
    //if (res.file) return window.location.href = res.file
    return ToastUtils.error('文件不存在')
  })
}
utils/transform.ts

/**
 * base64下载
 * @param text 文件内容
 * @param fileName 文件名
 * @param type 文件类型
 */
export function useDownloadByBase64(
  text: string,
  fileName: string,
  type = 'application/x-tar'
) {
  console.log('fileName: ', fileName)
  const at = `data:${type};base64,${text}`
  const blob = dataURLtoBlob(at)

  const href = window.URL.createObjectURL(blob)
  const aLink = document.createElement('a')
  aLink.href = href
  aLink.download = '测试版本'
  aLink.style.display = 'none'
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
  window.URL.revokeObjectURL(href)
}
/**
 * dataURLtoBlob
 * @param dataUrl 文件流string
 * @returns
 */
function dataURLtoBlob(dataUrl: string) {
  const arr = (dataUrl ?? '').split(',')
  const mime = arr[0].match(/:(.*?);/)![1]
  console.log('arr: ', arr, mime)
  const str = window.atob(arr[1])
  let n = str.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = str.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值