TypeScript中API返回字节数组转文件后损坏问题求助
问题:TypeScript生成的Excel文件损坏,字节序列转换异常
API响应格式
{ "fileName": "Pokemon.xlsx", "fileData":"文件的字节数组表示", "fileContent":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }
TypeScript代码实现
this.pokemonService.getExcel(REQUEST_OBJECT).subscribe((response) => { if (response) { const bytes = new Uint8Array(Buffer.from(response.fileData)); const fileBlob = new Blob([bytes], { type: response.contentType }); if (fileBlob.size > 0) { const link = document.createElement('a'); link.href = window.URL.createObjectURL(file); link.download = `${response.fileName}`; link.click(); } } else { //show error } });
响应接口定义
export interface PokemonResponse { fileData: ArrayBuffer; fileName: string; contentType: string; }
问题核心
- 生成的Excel文件打开提示损坏,转换为File对象后问题依旧
- 实际观察到
fileData是base64字符串形式,但接口定义为ArrayBuffer,TypeScript转换后的字节序列与C#调用结果不一致,推测转换逻辑错误
解决方案
1. 修正接口类型匹配
API返回的fileData是base64字符串,不是原生ArrayBuffer,先修正接口定义:
export interface PokemonResponse { fileData: string; // 改为string类型对应base64字符串 fileName: string; contentType: string; // 注意:API响应字段是fileContent,需统一字段名,否则type会丢失 }
2. 正确解码base64为二进制数据
使用浏览器原生API解码,避免Node.js的Buffer带来的兼容性问题:
this.pokemonService.getExcel(REQUEST_OBJECT).subscribe((response) => { if (response) { // 处理可能的base64前缀(如data:...;base64,) const base64Str = response.fileData.replace(/^data:.+;base64,/, ''); // 解码base64为二进制字符串 const binaryStr = atob(base64Str); // 转换为Uint8Array const bytes = new Uint8Array(binaryStr.length); for (let i = 0; i < binaryStr.length; i++) { bytes[i] = binaryStr.charCodeAt(i); } // 创建Blob并下载 const fileBlob = new Blob([bytes], { type: response.contentType || response.fileContent }); if (fileBlob.size > 0) { const link = document.createElement('a'); link.href = window.URL.createObjectURL(fileBlob); // 修正之前的变量名错误 link.download = response.fileName; link.click(); // 释放URL对象,避免内存泄漏 window.URL.revokeObjectURL(link.href); } } else { // 错误处理逻辑 } });
3. 关键注意事项
- 确保API返回的
fileData是纯净的base64字符串,无额外前缀 - 统一
contentType字段名:API响应里是fileContent,接口或API需调整为一致,否则Blob的MIME类型错误会导致文件损坏
内容的提问来源于stack exchange,提问作者Bug Hunter Zoro
相关产品推荐
相关产品推荐

