Chapter 6. Handling files

 

This chapter covers

  • Serving files to a client via HTTP
  • Receiving files from a client as an HTTP file upload

This chapter discusses how to implement file exchange over HTTP with Scalatra. As an example, you’ll build a basic document store application that acts as an HTTP-based file server. It will serve documents from the filesystem, and new documents can be uploaded by a client. The user interface is depicted in figure 6.1.

Figure 6.1. User interface for the document store example

6.1. Serving files

First we’ll discuss how to serve non-HTML files, such as text documents, web assets, and media files from a route. You’ll also learn how to serve static resources and how to apply gzip compression to HTTP responses.

6.1.1. Serving files through a route

A route can serve a file by returning a file as a result. There’s built-in support for the types java.io.File, java.io.InputStream, and scala.Array[Byte].

When the type of a returned value is supported, that value is written to the HTTP response body. The file itself can be read by the route’s action from various places, such as local or remote filesystems or databases:

get("/sample") {
  new File("images/cats.jpg")
}

6.2. Receiving files

6.3. Summary