[英]Getting Spring to map when getting JSON along with a file using multipart/form-data or multipart/mixed
I have a working solution but it seems silly that it's needed.我有一个可行的解决方案,但需要它似乎很愚蠢。
This is my working solution:这是我的工作解决方案:
@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....
The trouble is that fileData
is a String
object.问题是
fileData
是一个String
对象。 I would like to have spring map the JSON directly to my DocumentUploadFileData
class without having to do it myself as seen here: DocumentUploadFileData fileDataObj = objectMapper.readValue(fileData, DocumentUploadFileData.class);
我想让 spring 将 JSON 直接映射到我的
DocumentUploadFileData
类,而不必自己做,如下所示: DocumentUploadFileData fileDataObj = objectMapper.readValue(fileData, DocumentUploadFileData.class);
What I have tried:我尝试过的:
@RequestPart
I just used nothing.@RequestPart
我什么也@RequestPart
。 I actually thought that would be fine.@RequestBody
.@RequestBody
。 I thought for sure this would work.@ReqestBody
is intended for application/json requests and it doesn't like playing with multipart?@ReqestBody
是针对 application/json 请求的,它不喜欢玩多部分?DocumentUploadFileData
instead it fails and tells me it doesn't have a mapping strategy for the object?DocumentUploadFileData
它会失败并告诉我它没有对象的映射策略? I think something about the fact that it's a multipart request makes spring decide to use different mappers that maybe I need to add? I haven't used Spring for 3 years I'm sure the solution isn't that complicated, however, I still haven't gotten it after several hours.我已经 3 年没有使用 Spring 了,我确定解决方案并没有那么复杂,但是,几个小时后我仍然没有得到它。
Try to adept the following solution noted here: Spring MVC Multipart Request with JSON尝试熟练使用此处提到的以下解决方案: 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.