如何发送文件到浏览器下载? [英] How to send a file to browser for downloading?
问题描述
当客户端请求文件时,我使用这个代码发送:
When client request for a file, I use this code to send it:
public static Result download(String file) {
File file = getRealFile(file);
return Ok(file);
}
但是我发现浏览器不会下载,而是显示其内容。响应标题:
But I found the browser will not download it, but display its content instead. The response header:
Content-Type text/plain
Transfer-Encoding chunked
发送文件的方式是什么?
What's the correct way to send a file?
更新
根据Razvi的回答,我发现一个答案似乎对这个问题很好:https://stackoverflow.com/a/1074925/342235
Per Razvi's answer, I found an answer seems good for this question: https://stackoverflow.com/a/1074925/342235
但是我们真的有设置如此多的标题?
But do we really have to set so many headers?
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));
推荐答案
您需要设置Content-Disposition标题。我相信标题的值应该是附件
。请参阅操作回复文档。
You need to set the Content-Disposition header. I believe the value of the header should be attachment
. See Manipulating the response doc for this.
对于play 2.0,以下工作没有明确设置标题:
For play 2.0 the following works without explicitly setting the header:
ok(new FileInputStream(file))
这篇关于如何发送文件到浏览器下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!