I'm creating an API with Java, and I'm facing a problem with files.
This is my API definition:
@RequestMapping(value="/createUser", method = RequestMethod.POST)
ResponseEntity<?> fromFile(@RequestBody FileRequest FileRequest);
This FileRequest input Bean only have one item (while I solve the problem) but in future it will have more items such other form data as userName or userAge.
public class FromFileRequest {
@NotEmpty(message = "Value for input 'file' can't be null" )
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
In the angular side:
load(file: File): Observable<any> {
let formData: FormData = new FormData();
formData.append('file', file);
return this.apiService.post('/api/createFile', formData);
}
I receive an error in Java side
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.web.multipart.MultipartFile]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.web.multipart.MultipartFile` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) at [Source: (PushbackInputStream); line: 1, column: 9] (through reference chain: com.mypackage.api.dto.FileRequest["file"])
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:242) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
I really don't know if the problem is in angular or Java side, because if I just use the MultipartFile type as the input in my API (and modify angular properly) it works.
CodePudding user response:
You can not use a @RequestBody
you have to use a @RequestPart
@RequestMapping(value="/createUser", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
ResponseEntity<?> fromFile(@RequestPart(value = "file") MultipartFile file)
And if you need to send a DTO with your file,
- stringify it manually on the angular side :
formData.append('dto', JSON.stringify(data));
on the Java part add another
@RequestPart(value = "dto") String stringDTO)
call manually your object mapper :
YourDtoClass dto = objectMapper.readValue(stringDTO, YourDtoClass.class);
objectMapper
from package com.fasterxml.jackson.databind