使用 multipart/form-data 发送 POST 方法时 @ModelAttribute 出现问题

Problem with @ModelAttribute while sending POST method with multipart/form-data

由于我不明白的原因,我在处理多部分数据时遇到了问题。我无法反序列化地图。

控制器如下:

    @Override
    @PostMapping(value = "/attachments", produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<ResponseInfo> addAttachments(@ModelAttribute AddAttachment request) {
        return new ResponseEntity<>(subscriptionService.addAttachment(request.getSubscriptionIds(), request.getAttachment(), request.getDescription(),
                request.getUserName()), HttpStatus.CREATED);
    }

AddAttachment class:

    @NotEmpty(message = "The subscription IDs must not be null or empty.") Map<SubscriptionType,
            @NotEmpty(message = "Each list of subscriptions IDs must not be null or empty.")
                    Set<@NotBlank(message = "Each subscription ID must not be null, empty or blank.") String>> subscriptionIds;
    @NotBlank String description;
    @NotBlank String userName;
    @NotBlank MultipartFile attachment;

还有,Postman app上的案例,放一张图:

subscriptionId 的值:

{"DM_SUB": ["WLF1234-123456-12345678","WLF1234-123456-12345679"],
"EI_SUB": ["WLF1234-123456-12345678","WLF1234-123456-12345679"]}

它与枚举 SubscriptionType 匹配 而且,我看到的错误:

codes [typeMismatch.addAttachment.subscriptionIds,typeMismatch.subscriptionIds,typeMismatch.java.util.Map,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [addAttachment.subscriptionIds,subscriptionIds]; arguments []; default message [subscriptionIds]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Map' for property 'subscriptionIds'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map' for property 'subscriptionIds': no matching editors or conversion strategy found]]

我找不到将这个String转换成Map的方法。 有什么想法吗?

换个方法终于成功了

控制器:

    @PostMapping(value = "/attachments", produces = APPLICATION_JSON_VALUE, consumes = {APPLICATION_JSON_VALUE, MULTIPART_FORM_DATA_VALUE})
    public ResponseEntity<ResponseInfo> addAttachments(@RequestPart @NotBlank AddAttachment request, @RequestPart @NotBlank MultipartFile attachment) {
        return new ResponseEntity<>(alertService.addAttachment(request.getAlertIds(), attachment, request.getDescription(),
                request.getUserName()), HttpStatus.CREATED);
    }

添加附件class:

    @NotEmpty(message = "The subscription IDs must not be null or empty.") Map<SubscriptionType,
            @NotEmpty(message = "Each list of subscriptions IDs must not be null or empty.")
                    Set<@NotBlank(message = "Each subscription ID must not be null, empty or blank.") String>> subscriptionIds;
    @NotBlank String description;
    @NotBlank String userName;
    //No multipart file here.

来自 Postman 应用端:

结论:

  • 每个部分可以有不同的内容类型
  • 将文件与其余逻辑分开 (JSon)