java - 使用 multipart/form-data 或 multipart/mixed 在获取 JSON 和文件时让 Spring 进行映射

标签 java spring spring-boot spring-mvc

我有一个有效的解决方案,但似乎很愚蠢,需要它。

这是我的工作解决方案:

@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);

我尝试过的:

  1. 我什么也没用,而不是@RequestPart。我实际上认为那会很好。事实并非如此。
  2. 列表项@RequestBody。我想这肯定行得通。相反,它只是开始对我大喊大叫,说我的内容/类型无效?内容类型没有改变,但出于某种原因它希望它成为 application/json(即使我明确地说 multipart/form-data。我猜 @ReqestBody 是为 application/json请求但它不喜欢玩 multipart?
  3. 我也尝试过使用 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/

相关文章:

java - 将字符串数组从 JSP 页面传递到服务器

java - 无法解析的字符串 : [Unparseable date: "Wed May 29 16:34:58 ART 2013"] only on remote server

java - 从键盘输入并打印出星号

java - 我应该选择什么方式来代替乘法重载?

java - 检索 .wav 文件的标题、艺术家/作者和持续时间

java - spring如何从方法中获取args名称

java - 具有依赖于配置文件的加载的自定义 Spring 属性文件

spring - 如何避免在多模块 Gradle 项目中重复依赖版本?

java - 使用外部 Https 主机进行 Spring Boot 测试的 WireMock

java RMI概念