如何使用Webflux上传多个文件?
我发送内容类型为multipart/form-data
的请求,正文包含一个部分,其值是一组文件。
要处理单个文件,我按如下方式进行:
Mono<MultiValueMap<String, Part> body = request.body(toMultipartData());
body.flatMap(map -> FilePart part = (FilePart) map.toSingleValueMap().get("file"));
但是如何为多个文件做呢?
附言。还有其他方法可以在 webflux 中上传一组文件吗?
最佳答案
我已经找到了一些解决方案。 假设我们发送一个带有参数 files 的 http POST 请求,其中包含我们的文件。
注意响应是任意的
带有 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); }
关于java - 如何使用 Webflux 上传多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53778890/