Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


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));
like image 590
Freewind Avatar asked Jul 19 '12 10:07

Freewind


People also ask

How do I create a link to download a document?

Highlight the word you'd like to hyperlink and click on the hyperlink text symbol in order to add the link. Click on the search button next to the URL box and choose the file you would like to link. Don't forget to tick the This is a download box and click OK when you're finished. There you have it!

How do I let a file download?

You can usually download a file by clicking a link that says Download or a down-arrow icon. Downloaded files are saved to your computer, phone, or tablet's Downloads folder by default. To download a photo from the web, right-click the photo and choose the Save option.

What is the process of downloading a file?

Downloading is the transmission of a file or data from one computer to another over a network, usually from a larger server to a user device. Download can refer to the general transfer of data or to transferring a specific file. It can also be called to download, DL or D/L. All internet use requires downloading data.


1 Answers

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

like image 63
Razvi Avatar answered Oct 22 '22 23:10

Razvi