Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebFlux: Issues uploading file

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
like image 358
Marcos J.C Kichel Avatar asked Oct 07 '18 21:10

Marcos J.C Kichel


1 Answers

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()
}
like image 187
Bunthai Deng Avatar answered Nov 10 '22 01:11

Bunthai Deng