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

Next.js:如何避免响应中的Buffer格式CSV文件被解析为JSON?

解决方案

1. 修正API请求配置

你的API封装里明确设置了format: 'json',这会强制把响应按JSON解析,直接移除该配置,或添加二进制响应类型的设置:

this.request<{
/* @format binary */
file?: File
},
any
>({
path: '/safdsfa/download',
method: 'GET',
query: {code: '123'},
// 移除format: 'json',若API封装支持则添加以下配置
responseType: 'blob', 
})

如果直接使用fetch发起请求(替代现有api.getRequestCsv),写法如下:

const response = await fetch('/safdsfa/download?code=123');
if (!response.ok) throw new Error('请求失败');

2. 前端处理响应并触发下载

拿到二进制响应后,通过创建临时a标签触发浏览器下载:

try {
  const response = await fetch('/safdsfa/download?code=123');
  if (!response.ok) throw new Error('下载失败');
  
  // 从响应头提取文件名(也可手动指定)
  const contentDisposition = response.headers.get('Content-Disposition');
  let fileName = 'download.csv';
  if (contentDisposition) {
    const matches = contentDisposition.match(/filename="?([^"]+)"?/);
    if (matches?.[1]) fileName = matches[1];
  }
  
  // 将响应转为Blob对象
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  
  // 创建临时a标签触发下载
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  
  // 清理临时资源
  URL.revokeObjectURL(url);
  document.body.removeChild(a);
} catch (e) {
  console.error('下载出错:', e);
}

3. 优化服务器端响应头

补充编码和文件名编码配置,确保浏览器正确识别文件:

download(res: NextApiResponse, buffer: Buffer, fileName: string) {
  res.status(200);
  // 指定CSV的字符集为Shift_JIS
  res.setHeader('Content-Type', 'text/csv; charset=Shift_JIS');
  // 处理文件名编码,避免日文/中文乱码
  const encodedFileName = encodeURIComponent(fileName);
  res.setHeader(
    'Content-Disposition',
    `attachment; filename="${encodedFileName}"; filename*=UTF-8''${encodedFileName}`
  );
  res.send(buffer);
}

关键说明

  • 核心问题确实是前端将二进制CSV当作JSON解析,因此必须取消JSON格式解析配置,改用二进制响应处理逻辑。
  • 通过Blob和URL.createObjectURL可以直接让浏览器处理文件下载,无需手动解析内容。
  • 服务器端补充charset=Shift_JIS能确保浏览器用正确编码打开CSV,避免乱码;优化文件名编码可兼容不同浏览器的文件名显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:40:32