Return a stream with Spring MVC’s ResponseEntity

Spring’s InputStreamResource works well. You need to set the Content-Length manually, or it appears that Spring attempts to read the stream to obtain the Content-Length.

InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
httpHeaders.setContentLength(contentLengthOfStream);
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);

I never found any web pages suggesting using this class. I only guessed it because I noticed there were a few suggestions for using ByteArrayResource.

Leave a Comment