我正在使用 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 中的輸入(并正確修改角度),它就可以作業。
uj5u.com熱心網友回復:
你不能使用 a@RequestBody你必須使用 a@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));
在 Java 部分添加另一個
@RequestPart(value = "dto") String stringDTO)手動呼叫您的物件映射器:
YourDtoClass dto = objectMapper.readValue(stringDTO, YourDtoClass.class);
objectMapper從包裝com.fasterxml.jackson.databind
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/444865.html
