getFromFile
Signature
def getFromFile(fileName: String)(implicit resolver: ContentTypeResolver): Route
def getFromFile(file: File)(implicit resolver: ContentTypeResolver): Route
def getFromFile(file: File, contentType: ContentType): Route
Description
Allows exposing a file to be streamed to the client issuing the request.
The unmatchedPath
(see extractUnmatchedPath) of the RequestContext
RequestContext
is first transformed by the given pathRewriter
function, before being appended to the given directory name to build the final file name.
To files from a given directory use getFromDirectory. 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.
The file’s contents will be read using an Apache Pekko 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 Apache Pekko 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
-
source
import org.apache.pekko.http.scaladsl.server.directives._ import ContentTypeResolver.Default val route = path("logs" / Segment) { name => getFromFile(s"$name.log") // uses implicit ContentTypeResolver } // tests: Get("/logs/example") ~> route ~> check { responseAs[String] shouldEqual "example file contents" }
- Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.getFromFile; import static org.apache.pekko.http.javadsl.server.Directives.path; final Route route = path(PathMatchers.segment("logs").slash(segment()), name -> getFromFile(name + ".log")); // tests: testRoute(route).run(HttpRequest.GET("/logs/example")).assertEntity("example file contents");