Spring WebClient: How to stream large byte[] to file?
With recent stable Spring WebFlux (5.2.4.RELEASE as of writing):
final WebClient client = WebClient.create("https://example.com");
final Flux<DataBuffer> dataBufferFlux = client.get()
.accept(MediaType.TEXT_HTML)
.retrieve()
.bodyToFlux(DataBuffer.class); // the magic happens here
final Path path = FileSystems.getDefault().getPath("target/example.html");
DataBufferUtils
.write(dataBufferFlux, path, CREATE_NEW)
.block(); // only block here if the rest of your code is synchronous
For me the non-obvious part was the bodyToFlux(DataBuffer.class)
, as it is currently mentioned within a generic section about streaming of Spring's documentation, there is no direct reference to it in the WebClient section.
Stream upload 'POST' in Spring WebClient
Your first try was almost correct, however you need to use body(...)
instead of bodyValue(...)
:
body(BodyInserters.fromResource(new InputStreamResource(inputStream)))
This is because bodyValue(...)
wraps your resource inserter in a value inserter, which will then try to serialize the resource inserter itself and fail with the error you received.
Post file using webclient webflux to API accepting APPLICATION_OCTET_STREAM
This is how i was able to upload file
Step 1 : Read file as bytes array
bytes = new FileSystemResource((filePath)).getInputStream()
.readAllBytes();
Step 2 : pass the byte array to bodyValue
method
webClient.post()
.uri("Some-uri)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.bodyValue(bytes)
.retrieve()
.toBodilessEntity())
Spring WebClient BodyInserters.fromResource() changes content-type?
It happens because of the specific handling of the application/octet-stream
in ResourceHttpMessageWriter
. It tries to detect mime type by file extension.
You could use InputStreamResource
instead to keep application/octet-stream
var resource = new InputStreamResource(new FileInputStream(localFilename));
Related Topics
Get the Nearest Date to Specific from the List of Dates
Java: Getting a Substring from a String Starting After a Particular Character
Delete Everything After Part of a String
Gson Expected Begin_Array But Was String At Line 1 Column 62
Jackson Serializes a Zoneddatetime Wrongly in Spring Boot
How to Solve Gradle Error Cannot Find Symbol
How to Reconnect Kafka Producer Once Closed
Statefulbeantocsv With Column Headers
How to Get My Loops to Display Horizontally Instead of Vertically
How to Acknowledge Current Offset in Spring Kafka for Manual Commit
How to Upload a Document to Sharepoint With Java
How to Solve Maven 2.6 Resource Plugin Dependency
Cannot Find Element Using Selenium Webdriver
Automatically Convert Style Sheets to Inline Style
How to Get the Parent Element Name of a Child Element in Json
How to Read a File, Reverse the Order, and Write Reverse Order