如何将文件发送到浏览器进行下载?

Fre*_*ind 7 download playframework-2.0

当客户端请求文件时,我使用此代码发送它:

public static Result download(String file) {
    File file = getRealFile(file);
    return Ok(file);
}
Run Code Online (Sandbox Code Playgroud)

但我发现浏览器不会下载它,而是显示其内容.响应头:

Content-Type    text/plain
Transfer-Encoding   chunked
Run Code Online (Sandbox Code Playgroud)

发送文件的正确方法是什么?


更新

根据Per Razvi的回答,我发现这个问题的答案似乎很好:https://stackoverflow.com/a/1074925/342235

但我们真的必须设置这么多标题吗?

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filepath");
header("Content-Type: mime/type");
header("Content-Transfer-Encoding: binary");
// UPDATE: Add the below line to show file size during download.
header('Content-Length: ' . filesize($filepath));
Run Code Online (Sandbox Code Playgroud)

Raz*_*zvi 8

您需要设置Content-Disposition标头.我相信标题的值应该是attachment.请参阅为此操作响应文档.

对于play 2.0,以下工作无需显式设置标题:

ok(new FileInputStream(file))