Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to figure out how to pass a collection of optional parameters to a SpringBoot controller, along with a multipart file, but can't figure out how.

Without the multipart file, this works fine

public ResponseEntity<ViewModel> performOperationOnFilePath(@Valid @RequestBody final FileOperationFileContract requestBody) 

where FileOperationFileContract is a POJO that looks like this

public class FileOperationFileContract {
    @NotBlank(message = "The filepath is required")
    private String filePath;

    private Map<String, String> options = new HashMap<>();

    @JsonAnyGetter
    public Map<String, String> getOptions() {
        return options;
    }

    @JsonAnySetter
    public void setOptions(final String name, final String value) {
        options.put(name, value);
    }
}

Here's what I tried with the multipart file

public ResponseEntity<ViewModel> performOperationOnFile(@RequestParam(name="myfile") final MultipartFile file, @RequestPart(name="options", required=false) final FileOperationMultipartFileContract requestBody)

where FileOperationMultipartFileContract is a POJO that looks like this

public class FileOperationMultipartFileContract {
    private Map<String, String> options = new HashMap<>();

    @JsonAnyGetter
    public Map<String, String> getOptions() {
        return options;
    }

    @JsonAnySetter
    public void setOptions(final String name, final String value) {
        options.put(name, value);
    }
}

This seems to work if I specify the Json payload in Postman like this (note that I must specify the content-type as application/json, or I get the message "'application/octet-stream' not supported"

enter image description here

But if there is no json part sent, I get a 403. I want the option collection to just be empty or null. In other words, I want it to default to {}

I've tried RequestPart and RequestParam, but there's no difference. I've also tried it with and without the @Valid annotation

How can I do this?

Update: I think that I figured out that my problem does not have as much to do with Spring as it does with what I'm trying to do with the @JsonAnyGetter and @JsonAnySetter annotations. If I change FileOperationFileContract to have regular fields, it works. But my guess is that the way I have it doesn't work very well with null. Although if the value is null, there should be no calls to setOptions. Any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
6.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...