Setting HTTP headers in Play 2.0 (scala)?

后端 未结 1 416
执念已碎
执念已碎 2020-12-28 23: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; file

相关标签:
1条回答
  • 2020-12-29 00:31

    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.

    0 讨论(0)
提交回复
热议问题