WebFlux:问题上传文件

Mar*_*hel 5 java spring-webflux

我正在开发一个客户端,以使用webflux反​​应客户端上传文件:

这是我的客户端代码:

private Mono<String> postDocument(String authorization, InputStream content) {
    try {
        ByteArrayResource resource = new ByteArrayResource(IOUtils.toByteArray(content));
        return client.post().uri(DOCS_URI)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .header(HttpHeaders.AUTHORIZATION, authorization)
                .body(BodyInserters.fromMultipartData("file", resource))
                .exchange()
                .flatMap(res -> readResponse(res, String.class));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

服务器端代码:

    public Mono<ServerResponse> createDocument(ServerRequest request) {
    return request.body(toMultipartData())
            .flatMap(parts -> Mono.just((FilePart) parts.toSingleValueMap().get("file")))
            .flatMap(part -> {
                try {
                    String fileId = IdentifierFactory.getInstance().generateIdentifier();
                    File tmp = File.createTempFile(fileId, part.filename());
                    part.transferTo(tmp);
                    String documentId = IdentifierFactory.getInstance().generateIdentifier();
                    String env = request.queryParam("env")
                            .orElse("prod");
                    CreateDocumentCommand cmd = new CreateDocumentCommand(documentId, tmp, part.filename(), env);
                    return Mono.fromFuture(cmdGateway.send(cmd));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            })
            .flatMap(res -> ok().body(fromObject(res)));
}
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:

java.lang.ClassCastException: org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossPart cannot be cast to org.springframework.http.codec.multipart.FilePart
Run Code Online (Sandbox Code Playgroud)

Ign*_*tti -1

这对我有用

MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
bodyBuilder.part("file", new ClassPathResource("/bulk_upload/test.xlsx"));


List<DataFileAdjustment> list = webClient.post().uri("/bulk").accept(MediaType.APPLICATION_JSON)
        .body(BodyInserters.fromMultipartData(bodyBuilder.build()))
        .exchange()
        .expectStatus().isOk()
Run Code Online (Sandbox Code Playgroud)