You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中下载Int8Array类型Blob文件时出现base64编码问题如何解决

问题根因

你当前拿到的myFileByteArray并非原始xlsx文件的二进制字节数组,而是后端序列化时将byte[]转为base64字符串后,前端按二进制读取得到的base64文本对应的字节数组,所以直接生成Blob后导出的文件内容是base64编码文本,无法正常作为xlsx打开。

修复方案

前端临时修复

无需修改后端逻辑,直接在前端对base64内容做解码后再生成Blob,代码如下:

// 1. 将接收的Int8Array转为base64字符串
const base64Str = String.fromCharCode(...myFileByteArray);
// 2. 解码base64得到原始二进制字符串
const rawBinary = atob(base64Str);
// 3. 转换为Uint8Array用于生成Blob
const uint8Array = new Uint8Array(rawBinary.length);
for (let i = 0; i < rawBinary.length; i++) {
  uint8Array[i] = rawBinary.charCodeAt(i);
}
// 4. 生成Blob,注意xlsx的标准MIME类型不要写错
const blob = new Blob([uint8Array], {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});

// 下载逻辑优化,删除冗余代码,补充内存释放
const link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
const objectURL = URL.createObjectURL(blob);
link.href = objectURL;
link.download = this.myfile.name;
link.click();
// 释放临时URL,避免内存泄漏
URL.revokeObjectURL(objectURL);
document.body.removeChild(link);

后端优化方案(推荐)

从根源避免编码转换的性能损耗和出错概率:

  • Java REST接口不要将byte[]序列化为字符串返回,直接将二进制写入响应体,设置响应头:
    • Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    • Content-Disposition: attachment; filename=xxx.xlsx
  • Angular发起请求时配置responseType: 'blob',直接拿到可使用的Blob对象,无需额外转码。
注意事项

你向MSSQL存入varbinary的逻辑没有问题,编码问题出在Java接口到前端的序列化环节,Java序列化框架默认会将字节数组转为base64字符串传输,才会导致当前问题。

内容的提问来源于stack exchange,提问作者Hrvoje T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:15:00