在 Play 2.0 (scala) 中设置 HTTP 标头? [英] Setting HTTP headers in Play 2.0 (scala)?

查看:22
本文介绍了在 Play 2.0 (scala) 中设置 HTTP 标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有什么提示吗?

推荐答案

结果类型在play.api.mvc.Results中,见此处在 GitHub 上.

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

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!"))
}

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

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.

这篇关于在 Play 2.0 (scala) 中设置 HTTP 标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆