You need to enable JavaScript to run this app. Spring Boot如何动态设置Content-Type头且不被框架覆盖
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何动态设置Content-Type头且不被框架覆盖

Spring MVC动态设置下载接口Content-Type不被覆盖的解决方案

原写法中直接返回byte[]时,Spring的ByteArrayHttpMessageConverter会处理返回值并自动推断Content-Type,推断的优先级高于你提前在HttpServletResponse中设置的头,因此会将你设置的Content-Type覆盖。

方案1:使用ResponseEntity封装返回结果(推荐)

直接把响应头、响应体、状态码都封装到ResponseEntity中,Spring会直接使用你配置的头信息,不会进行覆盖:

@GetMapping("/download/{id}")
public ResponseEntity<byte[]> download(@PathVariable String id) throws Exception {
    // 从业务逻辑加载Document对象
    var doc = new Document("test.pdf", "application/pdf", "Base64 encoded data");
    
    byte[] fileContent = Base64.getDecoder().decode(doc.getData());
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", doc.getType());
    headers.add("Content-Disposition", "attachment; filename=\"%s\"".formatted(doc.getFilename()));
    
    return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}

该写法不需要注入HttpServletResponse,符合Spring MVC的接口设计规范,无需额外配置即可保证自定义头不被覆盖。

方案2:直接向Response输出流写数据(返回void)

如果需要继续使用HttpServletResponse对象,可以将方法返回值设为void,手动把文件内容写入响应输出流,Spring不会再走消息转换器的逻辑,自然不会覆盖你设置的头:

@GetMapping("/download/{id}")
public void download(@PathVariable String id, HttpServletResponse response) throws Exception {
    // 从业务逻辑加载Document对象
    var doc = new Document("test.pdf", "application/pdf", "Base64 encoded data");
    
    // 配置响应头,推荐用setHeader而非addHeader避免出现重复头
    response.setHeader("Content-Type", doc.getType());
    response.setHeader("Content-Disposition", "attachment; filename=\"%s\"".formatted(doc.getFilename()));
    
    byte[] fileContent = Base64.getDecoder().decode(doc.getData());
    try (OutputStream outputStream = response.getOutputStream()) {
        outputStream.write(fileContent);
        outputStream.flush();
    }
}

内容的提问来源于stack exchange,提问作者Jakub S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:45:04