2012-07-19 75 views
6

當客戶端請求的文件,我用這個代碼來發送:如何發送文件到瀏覽器進行下載?

public static Result download(String file) { 
    File file = getRealFile(file); 
    return Ok(file); 
} 

但我發現瀏覽器不會下載它,而是顯示其內容。響應標題:

Content-Type text/plain 
Transfer-Encoding chunked 

什麼是發送文件的正確方法?


更新

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

回答

8

您需要設置Content-Disposition標頭。我相信標題的值應該是attachment。請參閱Manipulating the response文檔。

關於播放2.0以下的作品沒有明確設置標題:

ok(new FileInputStream(file))

+0

我想play2有一些方便的方法來做到這一點,倒黴:) – Freewind 2012-07-19 11:52:28

+0

我找到了另一種方式來做到這一點,不需要明確設置標題。 :) – Razvi 2012-07-19 13:06:11

+0

'renderBinary'其中一個只用於播放1 :( – Freewind 2012-07-19 14:01:35

相關問題