Setting HTTP headers in Play 2.0 (scala)?

2019-02-02 15:44发布

问题:

I'm experimenting with the Play 2.0 framework on Scala. I'm trying to figure out how to send down custom HTTP headers--in this case, "Content-Disposition:attachment; filename=foo.bar". I can't seem to find documentation on how to do so (documentation on Play 2.0 is overall pretty sparse at this point).

Any hints?

回答1:

The result types are in play.api.mvc.Results, see here on GitHub.

In order to add headers, you'd write:

Ok
  .withHeaders(CONTENT_TYPE -> "application/octet-stream")
  .withHeaders(CONTENT_DISPOSITION -> "attachment; filename=foo.txt")

or

Ok.withHeaders(
  CONTENT_TYPE -> "application/octet-stream",
  CONTENT_DISPOSITION -> "attachment; filename=foo.txt"
)

And here is a full sample download:

def download = Action {
  import org.apache.commons.io.IOUtils
  val input = Play.current.resourceAsStream("public/downloads/Image.png")
  input.map { is =>
    Ok(IOUtils.toByteArray(is))
      .withHeaders(CONTENT_DISPOSITION -> "attachment; filename=foo.png")
  }.getOrElse(NotFound("File not found!"))
}

To download a file, Play now offers another simple way:

def download = Action {
  Ok.sendFile(new java.io.File("public/downloads/Image1.png"), fileName = (name) => "foo.png")
}

The disadvantage is that this results in an exception if the file is not found. Also, the filename is specified via a function, which seems a bit overkill.