Reputation: 51
@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);
}
Why I always get the file value is null, I've configure the multipart support,see below,
Upvotes: 5
Views: 12611
Reputation: 2517
This is what worked for me,
Previously my input
field was defined as,
<input type="file" />
I was getting null file with the above line but when I added the name="file"
everything worked fine!
<input type="file" name="file" />
Hope this helps!
Upvotes: 3
Reputation: 94469
The file should be binded to a RequestParam
instead of the RequestBody
as follows:
public ResponseEntity<ResponseEnvelope<String>> uploadFile(
@RequestParam("ownerId") Long ownerId,
@PathVariable("fileName") String fileName,
@RequestParam(value = "file") MultipartFile file)
This would correspond with the following HTML form:
<form method="post" action="some action" enctype="multipart/form-data">
<input type="file" name="file" size="35"/>
</form>
Then in your dispatcher configuration specify the CommonsMultiPartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
</bean>
Upvotes: 3