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

时间:2018-12-14 11:28:45

标签: java spring-boot spring-webflux

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

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

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

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

但是如何对多个文件执行此操作?

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

5 个答案:

答案 0 :(得分:5)

您可以使用Flux迭代哈希图并返回Flux

Flux.fromIterable(hashMap.entrySet())
            .map(o -> hashmap.get(o));

,它将与filepart一起作为数组发送

答案 1 :(得分:1)

我已经找到了一些解决方案。 假设我们发送带有参数 files 的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"));
    }
    
  2. 具有ModelAttribute的RestController

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

答案 2 :(得分:0)

键是使用 toParts 而不是 toMultipartData ,这更简单。这是与 RouterFunctions 一起使用的示例。

private Mono<ServerResponse> working2(final ServerRequest request) {
    final Flux<Void> voidFlux = request.body(BodyExtractors.toParts())
        .cast(FilePart.class)
        .flatMap(filePart -> {
            final String extension = FilenameUtils.getExtension(filePart.filename());
            final String baseName = FilenameUtils.getBaseName(filePart.filename());
            final String format = LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE);

            final Path path = Path.of("/tmp", String.format("%s-%s.%s", baseName, format, extension));
            return filePart.transferTo(path);
        });

    return ServerResponse
        .ok()
        .contentType(APPLICATION_JSON_UTF8)
        .body(voidFlux, Void.class);
}

答案 3 :(得分:0)

希望对你有帮助

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public JSON fileUpload(@RequestPart FilePart file)throws Exception{

    OSS ossClient = new OSSClientBuilder().build(APPConfig.ENDPOINT, APPConfig.ALI_ACCESSKEYID, APPConfig.ALI_ACCESSSECRET);
    File f = null;
    String url;
    try {
        String suffix = file.filename();
        String fileName = "images/" + file.filename();
        Path path = Files.createTempFile("tempimg", suffix.substring(1, suffix.length()));
        file.transferTo(path);
        f = path.toFile();
        ossClient.putObject(APPConfig.BUCKETNAME, fileName, new FileInputStream(f));
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        url = ossClient.generatePresignedUrl(APPConfig.BUCKETNAME, fileName, expiration).toString();
    }finally {
        f.delete();
        ossClient.shutdown();
    }
    return JSONUtils.successResposeData(url);
}

答案 4 :(得分:-1)

以下是使用WebFlux上传多个文件的工作代码。

@RequestMapping(value = "upload", method = RequestMethod.POST)
    Mono<Object> upload(@RequestBody Flux<Part> parts) {

        return parts.log().collectList().map(mparts -> {
            return mparts.stream().map(mmp -> {
                if (mmp instanceof FilePart) {
                    FilePart fp = (FilePart) mmp;
                    fp.transferTo(new File("c:/hello/"+fp.filename()));
                } else {
                    // process the other non file parts
                }
                return mmp instanceof FilePart ? mmp.name() + ":" + ((FilePart) mmp).filename() : mmp.name();
            }).collect(Collectors.joining(",", "[", "]"));
        });

    };
相关问题