我创建了一个 spring RestController 来处理来自 react js UI 的 fileUpload。
为了能够通过@Validated
注释使用自定义验证,必须将 MultipartFile 包装到一个类中,我将其命名为UploadedFile
. 创建了我的 Post Handler 方法,参数为@ModelAttribute
. 一切正常。
validate(target, error)
我的自定义验证器中的方法被调用,并且在 POST 处理程序方法中,UploadedFile
对象具有包含上传文档的多部分文件。
这是一个完美的工作代码
@PostMapping("/file")
public ResponseEntity<?> receiveFile(@Validated @ModelAttribute UploadedFile file) {
}
@Getter
@Setter
public class UploadedFile {
MultipartFile file;
}
// one CustomValidator class and webDataBinder.addValidators(customValidator) in controller
multipart.enabled=true //in application.properties
到目前为止一切都按预期工作,问题出现时
有人问我,这@ModelAttribute
是一个 Spring MVC 结构,因为这是一个微服务,将来除了我的 React UI 之外,它也会满足其他 api 请求,所以我应该使用@RequestParam
而不是@ModelAttribute
.
所以我@ModelAttribute
改为@RequestParam
如下
@PostMapping("/file")
public ResponseEntity<?> receiveFile(@Validated @RequestParam(name = "file") UploadedFile file)
但现在我得到了以下异常
Failed to convert value of type
'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile'
to required type 'com.x.x.x.UploadedFile';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type
'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile'
to required type 'com.x.x.x.UploadedFile':
no matching editors or conversion strategy found
如果,对于@RequestParam
,我改变类型,MultipartFile
而不是UploadedFile
然后我的 posthandler 被调用,但自定义验证器在处理程序调用之前没有被 spring 调用,我尝试MultiPartFile
在验证器支持方法中使用 instanceOf,但仍然无济于事。
@PostMapping(value="/file" )
public ResponseEntity<?> receiveFile(@Validated @RequestParam(name = "file") MultipartFile file)
我有办法通过代码显式调用自定义验证器方法作为 POST 处理程序中的第一行,所以我不需要解决方案我的问题是
怎么会,不添加任何自定义@Bean
或任何额外的外部依赖项,一切都可以在@ModelAttribut
e 上正常工作,但仅仅更改注释@RequestParam
是行不通的。