getFromDirectory

Signature

def getFromDirectory(directoryName: String)(implicit resolver: ContentTypeResolver): Route

Description

Allows exposing a directory’s files for GET requests for its contents.

The unmatchedPath (see extractUnmatchedPath) of the RequestContextRequestContext is first transformed by the given pathRewriter function, before being appended to the given directory name to build the final file name.

To serve a single file use getFromFile. To serve browsable directory listings use getFromBrowseableDirectories. To serve files from a classpath directory use getFromResourceDirectory instead.

Note that it’s not required to wrap this directive with get as this directive will only respond to GET requests.

Note

The file’s contents will be read using an Akka Streams Source which automatically uses a pre-configured dedicated blocking io dispatcher, which separates the blocking file operations from the rest of the stream.

Note also that thanks to using Akka Streams internally, the file will be served at the highest speed reachable by the client, and not faster – i.e. the file will not end up being loaded in full into memory before writing it to the client.

Example

Scala
val route =
  pathPrefix("tmp") {
    getFromDirectory("/tmp")
  }

// tests:
Get("/tmp/example") ~> route ~> check {
  responseAs[String] shouldEqual "example file contents"
}
Java
import static akka.http.javadsl.server.Directives.getFromDirectory;
import static akka.http.javadsl.server.Directives.pathPrefix;

final Route route = pathPrefix("tmp", () ->
  getFromDirectory("/tmp")
);

// tests:
testRoute(route).run(HttpRequest.GET("/tmp/example"))
  .assertEntity("example file contents");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.