后端返回base64文件流下载文件

文件名称最好取后端返回响应头中的Content-Disposition后面携带的(Content-Disposition: attachment;filename="XXXX.pdf")

一、后端返回base64文件流

说明:这个项目接口没有返回Content-Disposition,而是通过查询接口返回的,所以我取用的是接口返的

在这里插入图片描述

在这里插入图片描述

 async downloadFile(item) {
   let sysId = item.attachmentInfo.sysId
   let fileId = item.attachmentInfo.fileId
   let flowNode = this.$route.query.flowNode
   let result = await reqDownloadFile(JSON.stringify({ sysId, fileId, flowNode }))
   console.log('接口返回', result)
   if (result.operationSuccessFlag) {
   	 // 根据返回的文件名截取文件类型
     var type = item.attachmentInfo?.fileName.split('.')[1]
     let base64Url = this.getBase64Type(type) + result.file
     console.log('完整的base64', base64Url)
     this.downloadFileFn(base64Url, item.attachmentInfo?.fileName)
   } else {
     this.$toast(result.errorMessage)
   }
 },
 //根据文件后缀,添加base64前缀,拼接完整的base64
 getBase64Type(type) {
   switch (type) {
     case 'txt': return 'data:text/plain;base64,'
     case 'doc': return 'data:application/msword;base64,'
     case 'docx': return 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,'
     case 'xls': return 'data:application/vnd.ms-excel;base64,'
     case 'xlsx': return 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
     case 'pdf': return 'data:application/pdf;base64,'
     case 'pptx': return 'data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,'
     case 'ppt': return 'data:application/vnd.ms-powerpoint;base64,'
     case 'png': return 'data:image/png;base64,'
     case 'jpg', 'jpeg': return 'data:image/jpeg;base64,'
     case 'gif': return 'data:image/gif;base64,'
     case 'svg': return 'data:image/svg+xml;base64,'
     case 'ico': return 'data:image/x-icon;base64,'
     case 'bmp': return 'data:image/bmp;base64,'
   }
 },
 //将完整的base64码转换为blob
 base6toBlob(dataurl) {
   var arr = dataurl.split(","),
     mimeString = arr[0].match(/:(.*?);/)[1],
     str = atob(arr[1]),
     u8 = new Uint8Array(str.length)
   for (let i = 0; i < str.length; i++) {
     u8[i] = str.charCodeAt(i)
   }
   return new Blob([u8], { type: mimeString })
 },
 downloadFileFn(base64, fileName) {
   console.log('完整的base64', base64)
   console.log('下载后的文件名', fileName)
   var myBlob = this.base6toBlob(base64)
   var myUrl = URL.createObjectURL(myBlob)
   console.log('返回数据的blob链接', myUrl)
   // 使用a标签进行下载
   let link = document.createElement('a')
   link.style.display = 'none'
   link.href = myUrl
   link.setAttribute('download', fileName)//对下载的文件进行命名
   document.body.appendChild(link)
   link.click()
   document.body.removeChild(link) //下载完成移除元素
   window.URL.revokeObjectURL(myUrl) //释放掉blob对象
 }

二、后端返回字节流

在这里插入图片描述

如果后端返回的是上面格式,可以使用a标签下载,不用来回转换格式

  async downloadFile(item) {
    let sysId = item.attachmentInfo.sysId
    let fileId = item.attachmentInfo.fileId
    let flowNode = this.$route.query.flowNode
    let result = await reqDownloadFile(JSON.stringify({ sysId, fileId, flowNode }))
    console.log('接口返回', result)
    if (result.operationSuccessFlag) {
      let url = window.URL.createObjectURL(new Blob([result.file],))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', name)//对文件进行命名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
    } else {
      this.$toast(result.errorMessage)
    }
  },
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Uniapp 中,可以使用以下代码将后端返回base64 字符串下载为 Word 文件: ```javascript // 将 base64 字符串转换为 ArrayBuffer const base64ToArrayBuffer = (base64) => { const binary = atob(base64) const length = binary.length const buffer = new ArrayBuffer(length) const view = new Uint8Array(buffer) for (let i = 0; i < length; i++) { view[i] = binary.charCodeAt(i) } return buffer } // 将 ArrayBuffer 转换为文件并保存到本地 const saveBase64AsFile = (base64, filename) => { const arrayBuffer = base64ToArrayBuffer(base64) const blob = new Blob([arrayBuffer], { type: 'application/octet-stream' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = filename document.body.appendChild(link) link.click() document.body.removeChild(link) URL.revokeObjectURL(url) } // 下载 Word 文件 const downloadWordFile = () => { uni.request({ url: 'your api url', method: 'GET', responseType: 'arraybuffer', // 指定响应类型为 ArrayBuffer success: (res) => { const base64Str = btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')) // 将 ArrayBuffer 转换为 base64 字符串 const filename = 'your filename.docx' saveBase64AsFile(base64Str, filename) }, fail: (err) => { console.log(err) } }) } // 调用示例 downloadWordFile() ``` 其中,`downloadWordFile` 函数使用 `uni.request` 发送 GET 请求获取后端返回的 Word 文件的二进制数据,指定响应类型为 ArrayBuffer,然后将 ArrayBuffer 转换为 base64 字符串,并调用 `saveBase64AsFile` 函数将其下载为 Word 文件。在调用 `btoa` 函数将 ArrayBuffer 转换为 base64 字符串时,需要先将 ArrayBuffer 转换为 Uint8Array 类型,再使用 `reduce` 方法将其转换为字符串。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值