上传文件时,Spring REST MultipartFile文件始终为空

Ber*_*898 5 java spring spring-mvc

@RequestMapping(value = "{fileName:.+}", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<ResponseEnvelope<String>> uploadFile(
         @RequestParam("ownerId") Long ownerId, 
         @PathVariable("fileName") String fileName,
         @RequestBody MultipartFile file)
         throws Exception {
    ResponseEnvelope<String> env;
    if(null == certFileContent) {
        env = new ResponseEnvelope<String>("fail");
        return new ResponseEntity<ResponseEnvelope<String>>(env, HttpStatus.OK);
    }
    service.uploadCertificate(ownerId, fileName, certFileContent.getBytes());
    env = new ResponseEnvelope<String>("success");
    return new ResponseEntity<ResponseEnvelope<String>>(env, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

为什么我总是得到文件值为空,我已经配置了多部分支持,见下文,

Kev*_*sox 3

该文件应该绑定到 aRequestParam而不是RequestBody如下:

public ResponseEntity<ResponseEnvelope<String>> uploadFile(
         @RequestParam("ownerId") Long ownerId, 
         @PathVariable("fileName") String fileName,
         @RequestParam(value = "file") MultipartFile file)
Run Code Online (Sandbox Code Playgroud)

这将对应于以下 HTML 表单:

<form method="post" action="some action" enctype="multipart/form-data">
    <input type="file" name="file" size="35"/>
</form>
Run Code Online (Sandbox Code Playgroud)

然后在您的调度程序配置中指定CommonsMultiPartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
</bean>
Run Code Online (Sandbox Code Playgroud)