Sending an InputStream

For cases where a reference to a File object is not possible (for example resources in JAR files), Micronaut supports transferring input streams. To return a stream of data from the controller method, construct a StreamedFile.

The constructor for StreamedFile also accepts a java.net.URL for your convenience.

Sending a StreamedFile

  1. @Get
  2. public StreamedFile download() {
  3. InputStream inputStream = ...
  4. return new StreamedFile(inputStream, MediaType.TEXT_PLAIN_TYPE)
  5. // An attach(String filename) method is also available to set the Content-Disposition
  6. }

The server supports returning 304 (Not Modified) responses if the files being transferred have not changed, and the request contains the appropriate header. In addition, if the client accepts encoded responses, Micronaut encodes the file if appropriate. Encoding happens if the file is text-based and larger than 1KB by default. The threshold at which data is encoded is configurable. See the server configuration reference for details.

To use a custom data source to send data through an input stream, construct a PipedInputStream and PipedOutputStream to write data from the output stream to the input. Make sure to do the work on a separate thread so the file can be returned immediately.