如何使用Webflux上传多个文件? [英] How to upload multiple files using Webflux?

查看:162
本文介绍了如何使用Webflux上传多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to upload multiple files using Webflux?

我发送内容类型为 multipart/form-data 的请求,并且正文包含一个 part ,该值是一组文件.

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.还有另一种方法可以在webflux中上传一组文件吗?

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

推荐答案

我已经找到了一些解决方案.假设我们发送一个带有参数 files 的http POST请求,其中包含我们的文件.

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

注释响应是任意的

  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"));
}

  • 具有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
    }
    

  • 使用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);
    }
    

  • 这篇关于如何使用Webflux上传多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆