如何在DTO中添加Multipart列表并通过Postman调用REST接口
实现关联多文件的Test对象列表REST接口
一、代码实现
1. 数据传输对象(TestDto)
修改原Test类,添加文件列表字段:
@Data public class TestDto { private String emailId; private String firstName; private List<MultipartFile> files; }
2. 控制器接口调整
由于MultipartFile无法直接嵌入JSON对象,需将Test元数据和文件分开传递,再在控制器中完成绑定:
import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.List; import java.util.Map; @RestController public class TestController { @PostMapping(value = "/fileDto", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<?> test(@RequestPart("tests") List<TestDto> testDtos, @RequestParam Map<String, MultipartFile> allFiles) { // 通过参数名规则绑定文件到对应TestDto for (int testIndex = 0; testIndex < testDtos.size(); testIndex++) { TestDto currentTest = testDtos.get(testIndex); List<MultipartFile> assignedFiles = new ArrayList<>(); int fileIndex = 0; String fileParamName = testIndex + "-" + fileIndex; while (allFiles.containsKey(fileParamName)) { assignedFiles.add(allFiles.get(fileParamName)); fileIndex++; fileParamName = testIndex + "-" + fileIndex; } currentTest.setFiles(assignedFiles); // 打印验证绑定结果 System.out.println(currentTest); } return ResponseEntity.ok("submitted"); } }
二、Postman调用步骤
- 新建POST请求,填入接口URL(例:
http://localhost:8080/fileDto) - 切换到Body标签,选择
form-data格式 - 添加元数据参数:
- 参数名:
tests,类型选Text,格式选JSON,输入Test对象数组:[ { "emailId": "user1@test.com", "firstName": "Alice" }, { "emailId": "user2@test.com", "firstName": "Bob" } ]
- 参数名:
- 添加文件参数,遵循
{Test索引}-{文件索引}的命名规则:- 第一个Test的第一个文件:参数名
0-0,类型选File,选择本地PDF文件 - 第一个Test的第二个文件:参数名
0-1,类型选File,选择另一个PDF文件 - 第二个Test的第一个文件:参数名
1-0,类型选File,选择对应PDF文件
- 第一个Test的第一个文件:参数名
- 点击Send发送请求,验证控制台输出是否正确绑定了文件与Test对象
内容的提问来源于stack exchange,提问作者samee
相关产品推荐
相关产品推荐

