如何使用Webflux上传多个文件?

GVA*_*Art 12 java spring-boot spring-webflux

如何使用Webflux上传多个文件?

我发的内容类型请求:multipart/form-data与体包含一个组成部分,其值是一组文件.

要处理单个文件,请按以下步骤操作:

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

但是如何为多个文件做到这一点?

PS.还有另一种方法可以在webflux中上传一组文件吗?

GVA*_*Art 7

我已经找到了一些解决方案。假设我们发送一个包含我们文件的参数文件的 http POST 请求。

注意响应是任意的

  1. 带有 RequestPart 的 RestController

    @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"));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 带有 ModelAttribute 的 RestController

    @PostMapping("/upload-model")
    public Mono<String> processModel(@ModelAttribute Model model) {
        model.getFiles().forEach(it -> it.transferTo(Paths.get("/tmp/" + it.filename())));
        return Mono.just("OK");
    }
    
    class Model {
        private List<FilePart> files;
        //getters and setters
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 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);
    }
    
    Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用Flux迭代hashmap并返回Flux

Flux.fromIterable(hashMap.entrySet())
            .map(o -> hashmap.get(o));
Run Code Online (Sandbox Code Playgroud)

它将与filepart作为数组发送