6

I'm developing a client to upload a file using webflux reactive client:

This is my client-side code:

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

Server side code:

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

And I get this error:

java.lang.ClassCastException: org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossPart cannot be cast to org.springframework.http.codec.multipart.FilePart
Marcos J.C Kichel
  • 6,887
  • 8
  • 38
  • 78
  • I have similar issue (same error), but when I POST using `RestTemplate`, posing file from `curl` works just fine. The only difference I was able to notice is that `curl` uses `Expect: 100 redirect` header while `RestTemplate` uses `Connection: keep-alive`. – mpm Nov 29 '18 at 14:25
  • 1
    Hi, i use your client to request my service, and its working well, the solve is here https://stackoverflow.com/questions/53778890/how-to-upload-multiple-files-using-webflux – nekperu15739 Jan 24 '19 at 14:40

2 Answers2

0

I have sample code, but in Kotlin.
I hope it can help you.

1st way (save memory)


upload(stream: InputStream, filename: string): HashMap<String, Any> {
        val request: MultiValueMap<String, Any> = LinkedMultiValueMap();
        request.set("file", MultipartInputStreamFileResource(stream, filename))
        return client.post().uri("http://localhost:8080/files")
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .body(BodyInserters.fromMultipartData(request))
            .awaitExchange().awaitBody()
}

class MultipartInputStreamFileResource(inputStream: InputStream?, private val filename: String) : InputStreamResource(inputStream!!) {
        override fun getFilename(): String? {
            return filename
        }

        @Throws(IOException::class)
        override fun contentLength(): Long {
            return -1 // we do not want to generally read the whole stream into memory ...
        }

}

2nd way

//You wrote a file to somewhere in the controller then send the file through webclient

upload(stream: InputStream, filename: string): HashMap<String, Any> {
        val request: MultiValueMap<String, Any> = LinkedMultiValueMap();
        request.set("file", FileSystemResource(File("/tmp/file.jpg")))
        return client.post().uri("http://localhost:8080/files")
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .body(BodyInserters.fromMultipartData(request))
            .awaitExchange().awaitBody()
}

3rd way

upload(file: Part): HashMap<String, Any> {
        val request: MultiValueMap<String, Any> = LinkedMultiValueMap();
        request.set("file", file)
        return client.post().uri("http://localhost:8080/files")
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .body(BodyInserters.fromMultipartData(request))
            .awaitExchange().awaitBody()
}
Spring
  • 831
  • 1
  • 12
  • 42
-1

This worked for me

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()