我有一个处理文件上传的 Spring Boot 控制器方法,并且我尝试使用 @ModelAttribute 注释来绑定请求中的一些字段。这是我的控制器方法:
@PostMapping(value = "/{accountNo}/upload", consumes = "multipart/form-data")
public ResponseEntity<Object> uploadDocument(
@PathVariable Long accountNo,
@ModelAttribute RequestDTO requestDTO,
@RequestParam("file") MultipartFile file,
Authentication authentication) {
// ...
}
RequestDTO 类包含我想要从请求正文/表单数据绑定的字段。但是,我遇到了一个问题,方法中 requestDTO 对象始终为 null。
由于某些属性值的长度过长,通过请求参数传递DTO数据是不可行的。
我的设置中是否缺少某些内容,或者在这种情况下使用 @ModelAttribute 时是否存在任何常见陷阱?如何确保从请求中正确填充 requestDTO 对象?
我已验证请求是否已正确发送,包括 RequestDTO 的必填字段。
@RequestBody 注解不能与 multipart/form-data 一起使用。
我使用swagger以JSON格式发送数据。
{
"accountNo": "211100001201",
"kind": "hello",
"name": "string",
"url": "string",
"location": "string",
"storageStatus": "string",
"actionType": "string",
"value1": "string",
"detail": "string"
}
感谢您的协助!
你可以只添加dto而不需要任何注释,spring会自动将表单数据绑定到dto字段。
@PostMapping(value = "/{accountNo}/upload", consumes = "multipart/form-data")
public ResponseEntity<Object> uploadDocument(
@PathVariable Long accountNo,
RequestDTO requestDTO,
@RequestParam("file") MultipartFile file,
Authentication authentication) {
// ...
}
http://dolszewski.com/spring/how-to-bind-requestparam-to-object/
这将允许您在表单数据中输入 dto 的字段,它们将被映射到 dto 的字段。