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

Spring接口如何将byte[]作为MultipartFile响应返回给前端?

问题根因
  • 你当前直接将原始byte[]放入MultiValueMap返回,Spring MVC序列化时会默认调用字节数组的toString()方法,你看到的返回结果file=%5BB%4011a93325就是字节数组默认toString结果[B@11a93325的URL编码值,根本没有返回实际的文件二进制内容。
  • 同时缺少文件名、MIME类型等文件元数据声明,前端也无法将返回内容识别为正常文件。
正确实现方案

需要用ByteArrayResource包裹字节数组,同时补充文件元信息,改造后的代码如下:

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

// 类上的原有注解保留即可,这里仅给出改造后的接口方法
@PostMapping(value = "/getData", produces = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public ResponseEntity<MultiValueMap<String, Object>> getAttachmentDetails(@RequestBody Integer attachmentId) {
    MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
    // 1. 从数据库查询附件对应的字节数组、原始文件名、MIME类型(后两个字段建议存储在数据库中,无存储的话可按业务规则生成)
    byte[] fileBytes = emailIntakeService.getAttachmentDetails(attachmentId);
    String originalFilename = "测试附件.pdf"; // 替换为实际查询到的文件名,如xxx.docx、xxx.png
    String contentType = MediaType.APPLICATION_PDF_VALUE; // 替换为实际对应的文件MIME类型
    
    // 2. 用ByteArrayResource封装字节数组,重写方法返回文件名
    ByteArrayResource fileResource = new ByteArrayResource(fileBytes) {
        @Override
        public String getFilename() {
            return originalFilename;
        }
    };
    
    // 3. 配置文件对应的头信息
    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentDispositionFormData("file", originalFilename);
    fileHeaders.setContentType(MediaType.parseMediaType(contentType));
    
    // 4. 将封装好的文件实体加入表单数据
    formData.add("file", new HttpEntity<>(fileResource, fileHeaders));
    
    return ResponseEntity.ok(formData);
}
补充说明

如果你的业务场景不需要强制使用multipart/form-data格式返回,直接返回字节流加下载头的方案会更简单高效,前端可以直接触发下载,不需要额外解析form数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:15:02