Thursday, November 9, 2017

Spring Boot + Angular: Streaming Chunked Content

Imagine, if you will, that your server has a long job to do and it intermittently posts progress reports to a response stream.  As you can imagine you'd like to display these progress reports as they become available instead of having to wait for the entire job to finish.  This is a quick overview of how to do that with a Spring boot app that uses angular.

The Server

Spring boot makes it pretty easy to send back a response stream. 
Basically all we want to do is copy the InputStream to the OutputStream that's passed to StreaingResponseBody.writeTo.

The UI

We use the XMLHttpRequest in order to send an event as we get updates. This is all handled with angular's promises.


As a bonus what if you're using Jersey? Well the idea is the exact same as Spring's implementation where you're copying an InputStream to an OutputStream, but the classes are a little different is all. In essence you would do something like this.
final InputStream is = someService.runJobAndGetReportProgress();
StreamingOutput stream = (os) -> copyStream(is, os);
return Response.ok(stream).build();

No comments:

Post a Comment