Search code examples
spring-webfluxproject-reactorspring-data-r2dbc

Webflux upload file not saving


I have this piece of code:

@PostMapping(value = {"/store"})
public Mono<ResponseEntity<StoreResponse>> store(@RequestPart("file") Mono<FilePart> file,
                                                 @RequestPart("publicationId") String publicationId,
                                                 @RequestPart("visible") String visible) throws Exception {
    return file
            .doOnNext(this::checkFile)
            .flatMap((f) -> this.saveFileToDatabase(UUID.fromString(publicationId),
                    f.filename(),
                    Boolean.parseBoolean(visible)))
            .then(Mono.just(ResponseEntity.ok().body(new StoreResponse("", "", "Working",
                    null))))
            .onErrorReturn(ResponseEntity.internalServerError().body(new StoreResponse("Not Working",
                    "", "Working", null)));
}

Question 1:
Strange thing with this is that this works as long as i use flatMap on the Mono.
When i switch to map instead of flatMap then it does not work (the file will not be written to a database this.saveFileToDatabase (via spring-data-r2dbc)).
Why is this the way it is?

Question 2:
When i want to do another operation (save file to a minio container) after the saving to database - how can i chain this into the given code? Another then()?


Solution

  • When I switch to map instead of flatMap then it does not work

    map operator is designed to perform 1 to 1 synchronous operations like a simple object mapping. On the other hand, flatMap is used for asynchronous I/O operations like as in your case. See map vs flatMap in Reactor

    When i want to do another operation after the saving to database

    You could use a second flatmap like this:

     .flatMap(file -> this.saveFileToDatabase(...).map(reponse -> file))
     .flatMap(file -> this.saveFileToContainer(...))