How to send a file to the browser for download?

When requesting a client 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 that the browser does not load it, but displays its contents. Answer Header:

 Content-Type text/plain Transfer-Encoding chunked 

What is the correct way to send a file?


Update

In response to Razvi, I found the answer seems to be good for this question: https://stackoverflow.com/a/2208778

But do we really need 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)); 
+6
source share
1 answer

You need to set the Content-Disposition header. I believe the header value should be attachment . See Manipulating a doc response for this.

For playback 2.0, the following is done without explicitly setting the title:

ok(new FileInputStream(file))

+8
source

Source: https://habr.com/ru/post/920879/


All Articles