Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting HTTP headers in Play 2.0 (scala)?

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?

like image 370
Ben Dilts Avatar asked Nov 20 '11 04:11

Ben Dilts


1 Answers

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.

like image 98
Marius Soutier Avatar answered Sep 22 '22 02:09

Marius Soutier