-1

I have a service that serve the uploading picture to server. I used Java Spring Reactive on this service, I rename the file with dateformat and need to return this new name. This is what i do in my service :

@Override
public Mono<String> createImage(Flux<FilePart> files) {
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    final String[] fileName = {""};

    return files.flatMap(file -> {
        Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, dateFormat.format(date) + "." + FilenameUtils.getExtension(file.filename())).toFile())
                .log("createImage-picktarget").map(destFile -> {
                    try {
                        fileName[0] = dateFormat.format(date) + "." + FilenameUtils.getExtension(file.filename());
                        destFile.createNewFile();
                        return destFile;
                    } catch (IOException ioe) {
                        throw new RuntimeException(ioe);
                    }
                }).log("createImage-newFile").flatMap(file::transferTo).log("createImage-copy");

        return Mono.when(copyFile).log("createImage-when");
    }).log("createImage-flatMap").then(Mono.just(fileName[0])).log("createImage-done");
}

this code return Mono to my controller. In this controller i need to return the String in Mono to the client because this string contain the new uploaded filename that needed in the frontend. This is my controller :

@PostMapping(value = "/upload")
public Mono<String> createFile(@RequestPart(name = "file")Flux<FilePart> files){
    Mono<String> saveImage = nasabahService.createImage(files);

    return saveImage.flatMap(value -> Mono.just(value));

}

My question is, how can I get the String from Mono that returned by createImage function so I can send it to the client?

Thanks for your help.

user1290932
  • 207
  • 1
  • 6
  • 19

1 Answers1

0

In first place, if you want to build a reactive service you should return a Mono object and let spring using SSE (server sent events) to deliver the string to the front in a non-blocking way. Anyway, I don't understand why you do the last flatmap you can return the saveImage directly from the controller.

And if you really need to return the string instead of the mono object you have to block it and obtain the result using .block() method from Mono API

JArgente
  • 2,239
  • 1
  • 9
  • 11