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

Java8 Spring Excel直接下载问题:返回Blob而非自动触发下载

解决Java Spring接口返回Excel在Postman中无法自动下载的问题

问题原因

Postman对POST请求的默认处理逻辑不会自动触发文件下载,而是直接展示响应的二进制内容(即你看到的乱码Blob);同时后端Header设置也有可优化空间,能帮助客户端更准确识别文件类型。

解决方案

1. 调整Postman请求设置

发送请求前完成以下操作:

  • 打开当前请求的「Settings」面板(请求页签右侧的齿轮图标)
  • 关闭「Automatically follow redirects」选项
  • 在请求的「Body」标签页,选择「Send and download」按钮(替代默认的「Send」)
    发送后Postman会直接弹出文件保存对话框,无需手动点击「保存为文件」。

2. 优化后端代码的Header配置

修改接口代码,调整Header设置以更精准适配Excel文件:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;

@PostMapping(value = "/download-report")
public ResponseEntity<Resource> getSrmTallyReportInExcel() {
    try {
        File file = /* 你的文件创建/赋值逻辑 */;
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        
        HttpHeaders headers = new HttpHeaders();
        // 使用Excel专用的Content-Type,替代通用二进制流类型
        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        // 用ContentDisposition构建器明确指定附件,兼容更多客户端
        headers.setContentDisposition(org.springframework.http.ContentDisposition.attachment()
                .filename("report.xlsx")
                .build());
        // 添加文件长度Header,让客户端知晓文件大小
        headers.setContentLength(file.length());
        
        return ResponseEntity.ok().headers(headers).body(resource);
    } catch (IOException e) {
        // 补充异常处理逻辑,返回错误响应
        return ResponseEntity.internalServerError().build();
    }
}

代码修改说明:

  • 移除produces注解,避免与Header中指定的Content-Type冲突
  • 将Content-Type改为Excel xlsx文件的标准MIME类型,帮助客户端准确识别文件类型
  • 使用Spring官方推荐的ContentDisposition构建器设置附件信息,比setContentDispositionFormData更规范
  • 添加Content-Length Header,提升客户端处理文件的体验
  • 完善异常捕获逻辑,替换空catch块,增加错误响应返回

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:12:45