在Play 2.0(scala)中设置HTTP标头? [英] Setting HTTP headers in Play 2.0 (scala)?
问题描述
我正在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
中,请参见
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"
)
这是完整的示例下载:
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屋!