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

时间:2013-12-19 10:04:34

标签: 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);
}

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

         

2 个答案:

答案 0 :(得分:3)

这对我有用,

以前我的input字段定义为,

<input type="file" />

我使用上面的行获取了null文件,但是当我添加name="file"时,一切正常!

<input type="file" name="file" />

希望这有帮助!

答案 1 :(得分:2)

该文件应绑定到RequestParam而不是RequestBody,如下所示:

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

这与以下HTML表单相对应:

<form method="post" action="some action" enctype="multipart/form-data">
    <input type="file" name="file" size="35"/>
</form>

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

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
</bean>