我有一个有效的解决方案,但似乎很愚蠢,需要它。
这是我的工作解决方案:
@PreAuthorize("isAuthenticated()")
@ApiOperation(value = "Takes in a document.", nickname = "Document Upload", response = DocumentResponse[].class)
@ResponseStatus(HttpStatus.ACCEPTED)
@RequestMapping(
value = "/api/v1/document/upload",
produces = "application/json",
consumes = "multipart/form-data",
method = RequestMethod.POST)
public DocumentResponse uploadDocument(
// THIS is where I am using a String and don't want to.
@RequestPart("fileData") String fileData,
@RequestPart("file") MultipartFile file,
@RequestHeader("idempotency-id") String idempotencyId) throws IOException {
// THIS is the line I would also like to avoid.
DocumentUploadFileData fileDataObj = objectMapper.readValue(fileData, DocumentUploadFileData.class);
printBeanValues(fileDataObj);
More after....
问题在于 fileData
是一个 String
对象。我想让 spring 将 JSON 直接映射到我的 DocumentUploadFileData
类,而不必自己动手,如下所示:DocumentUploadFileData fileDataObj = objectMapper.readValue(fileData, DocumentUploadFileData.class);
我尝试过的:
- 我什么也没用,而不是
@RequestPart
。我实际上认为那会很好。事实并非如此。 - 列表项
@RequestBody
。我想这肯定行得通。相反,它只是开始对我大喊大叫,说我的内容/类型无效?内容类型没有改变,但出于某种原因它希望它成为 application/json(即使我明确地说 multipart/form-data。我猜@ReqestBody
是为 application/json请求但它不喜欢玩 multipart? - 我也尝试过使用 RequestParam,如果我使用 String 作为对象,它确实有效。如果我尝试使用我的
DocumentUploadFileData
而不是它失败并告诉我它没有对象的映射策略?我认为这是一个多部分请求这一事实使得 spring 决定使用可能我需要添加的不同映射器?我知道多部分请求使用边界并且通常略有不同,因此它可能需要不同的解决方案是有道理的。我只是不知道如何提供。
我已经 3 年没有使用 Spring 我确信解决方案没有那么复杂,但是,几个小时后我仍然没有得到它。
最佳答案
尝试采用此处记录的以下解决方案:Spring MVC Multipart Request with JSON
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
关于java - 使用 multipart/form-data 或 multipart/mixed 在获取 JSON 和文件时让 Spring 进行映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54470645/