19

I'm using Play Framework 2.0.3 to create an application which delivers Excel files that should be downloadable by the user.

 response().setContentType("application/x-download");  
 response().setHeader("Content-disposition","attachment; filename=tradeLogTest.xlsx");  

but,how to get the outputstream from response()?tks

biesior
  • 55,576
  • 10
  • 125
  • 182
ma nicolas
  • 195
  • 1
  • 1
  • 5

3 Answers3

42

Play's action can return a File:

response().setContentType("application/x-download");  
response().setHeader("Content-disposition","attachment; filename=tradeLogTest.xlsx"); 
return ok(new File("/absolute/path/to/tradeLogTest.xlsx"));

Here's an API for Results

biesior
  • 55,576
  • 10
  • 125
  • 182
  • 14
    In Scala there is a shortcut : Ok.sendFile(new java.io.File(myFile)). Maybe it's the same for Java – Julien Lafont Dec 18 '12 at 23:28
  • 5
    [Here](http://www.playframework.com/documentation/2.0.1/ScalaStream) are the official docs for @JulienLafont's shortcut. – mjswensen Sep 03 '13 at 22:50
  • 1
    Does it support resume? – Saeed Zarinfam Jun 11 '14 at 09:50
  • how is it possible to force for example chrome, to open the file (if PDF) with its internal PDF viewer? – behzad May 29 '15 at 14:48
  • @behzad use `content-disposition inline` (http://stackoverflow.com/q/1395151/1066240) anyway keep in mind that finally browser determines how to handle files (display or download) – biesior May 29 '15 at 15:00
  • thanks @biersior! I also have another question! what will happen if I do not set the ContentType? I tried it and it worked fine. for example I didnt set the ContentType, once I uploaded a .exe file, once a .pdf and for downloading, both chrome and IE handled them fine. – behzad May 29 '15 at 16:00
  • That depends from browser, they will just exec default action... while in this question asked for exactly opposite solution - download file instead opening – biesior May 29 '15 at 16:02
7

Providing download option for static files can be done in Play as:

Ok.sendFile(new File("path to file/abc.csv"), inline=true).withHeaders(CACHE_CONTROL->"max-age=3600",CONTENT_DISPOSITION->"attachment; filename=abc.csv", CONTENT_TYPE->"application/x-download");

There are other parameters that are also available

For Internet Explorer - make sure you set the Content Disposition

AJ.P
  • 406
  • 5
  • 8
0

Serving files If it’s not a problem to load the whole content into memory for simple content what about a large data set? Let’s say we want to send back a large file to the web client.

read more at : http://www.playframework.com/documentation/2.0.x/JavaStream

teeyo
  • 3,665
  • 3
  • 22
  • 37