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

求助:使用Axios处理Java后端返回的二进制字节数组问题

解决Axios接收二进制字节数组被转为字符串的问题

问题根源

Axios默认会将响应数据按UTF-8编码解析为字符串,而你后端返回的workbook是二进制字节数组,这种自动解析会破坏原始二进制数据,最终导致它变成乱码字符串。

正确处理步骤

1. 配置Axios的响应类型

发起请求时,必须明确指定responseType为'arraybuffer',阻止Axios自动将二进制数据转为字符串:

axios.post('/你的API地址', 请求参数, {
  responseType: 'arraybuffer'
})
.then(response => {
  // 先把arraybuffer转成UTF-8字符串,再解析为JSON对象
  const jsonStr = new TextDecoder('utf-8').decode(response.data);
  const resObj = JSON.parse(jsonStr);
  
  // 将workbook的数字数组转为Uint8Array格式的二进制数据
  const workbookBuffer = new Uint8Array(resObj.workbook);
  
  // 示例:将二进制数据转为Blob并下载Excel文件
  const blob = new Blob([workbookBuffer], { 
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
  });
  const downloadUrl = URL.createObjectURL(blob);
  const aTag = document.createElement('a');
  aTag.href = downloadUrl;
  aTag.download = '导出文件.xlsx';
  aTag.click();
  URL.revokeObjectURL(downloadUrl);
})
.catch(err => {
  console.error('请求出错:', err);
});

2. 后端优化方案(可选)

如果后端可以调整,建议把二进制文件和userId分开返回:将userId放在响应头中,Excel二进制数据作为响应体直接返回,前端处理会更简洁:

axios.post('/你的API地址', 请求参数, {
  responseType: 'blob'
})
.then(response => {
  // 从响应头获取userId
  const userId = response.headers['x-user-id'];
  // 响应体直接是Blob格式的Excel文件
  const excelBlob = response.data;
  
  // 后续下载或处理逻辑同上
})

核心注意事项

  • 一定要设置responseType为arraybuffer或blob,避免Axios自动解析二进制数据
  • 当响应是包含二进制数组的JSON结构时,需先将arraybuffer转成UTF-8字符串,解析为JSON后再把数字数组转为Uint8Array处理二进制数据

内容的提问来源于stack exchange,提问作者Dattatreya Kugve

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:47:03