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

Angular导出Excel报错:TypeError: Cannot read 'name' of undefined

解决方案

1. 修复saveAs调用的直接错误

你遇到的TypeError: Cannot read properties of undefined (reading 'name'),根源是把Blob对象当成了带body属性的响应对象。当Angular的HTTP请求返回Blob类型时,response本身就是Blob实例,不需要取response.body。

把原代码:

saveAs(response.body, fileName);

修改为:

saveAs(response, fileName);

2. 获取后端生成的文件名

后端生成的文件名需要通过响应头的Content-Disposition字段返回,前端需从HTTP响应头中解析该值:

Angular端解析逻辑

发起请求时,必须设置observe: 'response'以获取包含响应头的完整响应对象,再解析Content-Disposition:

this.httpClient.get('/api/export', {
  responseType: 'blob',
  observe: 'response'
}).subscribe((response) => {
  // 解析响应头中的文件名
  const contentDisposition = response.headers.get('Content-Disposition');
  let fileName = 'exported_data.xlsx'; // 设置默认文件名
  if (contentDisposition) {
    const matches = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
    if (matches != null && matches[1]) {
      fileName = matches[1].replace(/['"]/g, '');
    }
  }
  // 执行下载
  saveAs(response.body, fileName);
});

3. 后端ASP.NET Core的配套配置

要让前端能读取到Content-Disposition响应头,后端需完成两项配置:

接口中设置响应头

[HttpGet("export")]
public IActionResult ExportData([FromQuery] FilterParams filter)
{
    // 生成Excel文件的逻辑,得到memoryStream和自定义fileName
    var memoryStream = GenerateExcel(filter);
    var fileName = $"Data_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

    // 添加下载响应头
    Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");
    // 允许前端读取该响应头(CORS场景必须配置)
    Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

CORS策略暴露响应头

在Program.cs中配置CORS时,明确允许暴露Content-Disposition头:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader()
              .WithExposedHeaders("Content-Disposition"); // 关键配置
    });
});

// 启用CORS中间件
app.UseCors("AllowAll");

4. 排查要点

  • 若未设置observe: 'response',Angular默认仅返回响应体(Blob),无法获取响应头。
  • 后端必须配置Access-Control-Expose-Headers,否则浏览器会隐藏Content-Disposition这类非默认响应头。
  • 确认后端返回的Content-Disposition格式正确,必须包含filename参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:28:06