在 Play 2.0 (scala) 中设置 HTTP 标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8199490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:41:04  来源:igfitidea点击:

Setting HTTP headers in Play 2.0 (scala)?

scalaplayframeworkplayframework-2.0

提问by Ben Dilts

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).

我正在 Scala 上试验 Play 2.0 框架。我正在尝试弄清楚如何发送自定义 HTTP 标头——在这种情况下,“Content-Disposition:attachment; filename=foo.bar”。我似乎找不到有关如何执行此操作的文档(此时 Play 2.0 上的文档总体上非常稀少)。

Any hints?

任何提示?

回答by Marius Soutier

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

结果类型在 中play.api.mvc.Results,请参阅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:

要下载文件,Play 现在提供了另一种简单的方法:

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.

缺点是如果找不到文件,这会导致异常。此外,文件名是通过函数指定的,这似乎有点矫枉过正。