Sending an InputStream

For cases where a reference to a File object is not possible (for example resources contained within JAR files), Micronaut supports transferring of 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 will encode the file if it is deemed appropriate. Encoding will happen if the file is text based and greater than 1KB by default. The threshold at which data will be 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 allow writing 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.