我正在使用Java创建一个API,而我在文件方面也面临着一个问题。
这是我的API定义:
@RequestMapping(value="/createUser", method = RequestMethod.POST)
ResponseEntity<?> fromFile(@RequestBody FileRequest FileRequest);
这个FileRequest输入Bean只有一个项(当我解决问题时),但将来它将有更多的项,如userName或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;
}
}
在角边:
load(file: File): Observable<any> {
let formData: FormData = new FormData();
formData.append('file', file);
return this.apiService.post('/api/createFile', formData);
}
我在Java端收到一个错误
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]
我真的不知道问题是在角度方面还是在Java方面,因为如果我只使用MultipartFile类型作为API中的输入(并正确地修改角),它就能工作。
发布于 2022-03-16 08:45:01
您不能使用@RequestBody
,您必须使用@RequestPart
@RequestMapping(value="/createUser", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
ResponseEntity<?> fromFile(@RequestPart(value = "file") MultipartFile file)
如果你需要用你的文件发送一个DTO,
formData.append('dto', JSON.stringify(data));
@RequestPart(value = "dto") String stringDTO)
部件上的
YourDtoClass dto = objectMapper.readValue(stringDTO, YourDtoClass.class);
objectMapper
来自包com.fasterxml.jackson.databind
https://stackoverflow.com/questions/71493907
复制相似问题