9

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 Answer 1

28

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The withHeaders method can be called once with multiple tuple parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.