How to upload multiple files using Webflux?

GVArt :

How to upload multiple files using Webflux?

I send request with content type: multipart/form-data and body contains one part which value is a set of files.

To process single file I do it as follow:

Mono<MultiValueMap<String, Part> body = request.body(toMultipartData());
body.flatMap(map -> FilePart part = (FilePart) map.toSingleValueMap().get("file"));

But how to done it for multiple files?

PS. Is there another way to upload a set of files in webflux ?

GVArt :

I already found some solutions. Let's suppose that we send an http POST request with an parameter files which contains our files.

Note responses are arbitrary

  1. RestController with RequestPart

    @PostMapping("/upload")
    public Mono<String> process(@RequestPart("files") Flux<FilePart> filePartFlux) {
        return filePartFlux.flatMap(it -> it.transferTo(Paths.get("/tmp/" + it.filename())))
            .then(Mono.just("OK"));
    }
    
  2. RestController with ModelAttribute

    @PostMapping("/upload-model")
    public Mono<String> processModel(@ModelAttribute Model model) {
        model.files.forEach(it -> it.transferTo(Paths.get("/tmp/" + it.filename())));
        return Mono.just("OK");
    }
    
    class Model {
        private List<FilePart> files;
        //getters and setters
    }
    
  3. Functional way with HandlerFunction

    public Mono<ServerResponse> upload(ServerRequest request) {
        Mono<String> then = request.multipartData().map(it -> it.get("files"))
            .flatMapMany(Flux::fromIterable)
            .cast(FilePart.class)
            .flatMap(it -> it.transferTo(Paths.get("/tmp/" + it.filename())))
            .then(Mono.just("OK"));
    
        return ServerResponse.ok().body(then, String.class);
    }
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36239&siteId=1