How to send a file to browser for downloading?

别说谁变了你拦得住时间么 提交于 2020-01-11 02:18:06

问题


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?


Update

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

回答1:


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.

For play 2.0 the following works without explicitly setting the header:

ok(new FileInputStream(file))



来源:https://stackoverflow.com/questions/11559304/how-to-send-a-file-to-browser-for-downloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!