@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,
The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storages will be cleared at the end of request processing.
MultipartFile multipartFile = new MockMultipartFile("sourceFile. tmp", "Hello World". getBytes()); File file = new File("src/main/resources/targetFile. tmp"); try (OutputStream os = new FileOutputStream(file)) { os.
FileInputStream inputFile = new FileInputStream( "path of the file"); MockMultipartFile file = new MockMultipartFile("file", "NameOfTheFile", "multipart/form-data", inputFile); now use the file input as multipart file.
By default, Spring does no multipart handling, because some developers want to handle multiparts themselves. You enable Spring multipart handling by adding a multipart resolver to the web application's context. Each request is inspected to see if it contains a multipart.
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>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With