Skip to content

File and Resource Directives

Mathias edited this page Mar 8, 2012 · 4 revisions

Many web services also need to serve a small number of static files, e.g. for documentation purposes. spray makes this easy by defining a few directives that serve content from the file system or application JAR(s):

  • getFromFileName
  • getFromFile
  • getFromResource
  • getFromDirectory
  • getFromResourceDirectory

getFromFileName, getFromFile and getFromResource respond to GET requests with the contents of a given file or (JAR) resource, e.g.:

path("api" / "documentation") {
  getFromFile("/var/www/fancy-service/doc.html")
}

The -directory variants serve up whole directories. The following route for example

pathPrefix("api" / "documentation") {
  getFromDirectory("/var/www/fancy-service/documentation/")
}

will respond to GET requests to /api/documentation/chapter/1.html with the contents of the file /var/www/fancy-service/documentation/chapter/1.html.

In order to allow for some more URI flexibility you can also supply getFromDirectory and getFromResourceDirectory with a "path rewriter" function argument String => String, which allows for custom preprocessing of the relevant path segment, before it is passed on to the file system. You might for example use it to append ".html" extensions for files that don't have one.

The getFrom... directives automatically set the content type of the HTTP response to the media type matching the file extension. For example ".html" files will be served with Content-Type: text/html while ".txt" files will receive a Content-Type: text/plain. You can also very easily supply your own media-types and/or file extensions. See the Custom Media Types chapter for further documentation on this.

File Streaming

If your application needs to serve large files it makes sense to stream their contents using the HTTP/1.1 "chunked" transfer-encoding. This way the file contents don't have to be loaded into memory in their entirety and responsiveness will be improved since the application can sent out content chunks as they are read from disk.

As discussed in the Configuration chapter spray supports two settings for this: 'file-chunking-threshold-size' and 'file-chunking-chunk-size'. The former defines the minimal file size triggering content streaming while the latter defines the size of an individual chunk (both values are in bytes).

You enable content streaming by setting 'file-chunking-threshold-size' to some value less than Long.MaxValue. The 'file-chunking-chunk-size' setting has a default value of 512 Kb.

Clone this wiki locally