Sunday, June 12, 2016

How to attach CSV file to Play application response

Play makes it easy to manipulate a HTTPResponse. You can find in the manual, how to add headers, set cookies etc. in a response. This post shows how to attach a CSV file to a HTTPResponse.

The implementation differs according to the use case:
  • Some string source is converted to csv file while sending to the client.
  • An existing csv file is sent to the client.

Sending string as CSV file in a HTTPResponse


Play 2.4:
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result string2CsvFile() {  
   String csvContent = "f1,f2,f3,f4";  
   response().setContentType("text/csv");  
   response().setHeader(CONTENT_DISPOSITION,   
       String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));  
   return ok(new ByteArrayInputStream(csvContent.getBytes()));  
}  

Play 2.5:
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result string2CsvFile() {  
   String csvContent = "f1,f2,f3,f4";  
    response().setHeader(CONTENT_DISPOSITION, 
            String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
    return ok(new ByteArrayInputStream(csvContent.getBytes())).as("text/csv");
}  

Sending existing CSV file in a HTTPResponse


Play 2.4:
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result attachCsvFile() {  
    response().setContentType("text/csv");
    response().setHeader(CONTENT_DISPOSITION, 
            String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
    return ok(Play.application().getFile(CSV_FILE));
}  

Play 2.5:
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result attachCsvFile() {  
    response().setHeader(CONTENT_DISPOSITION, 
            String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
    return ok(Play.current().getFile(CSV_FILE)).as("text/csv");}  

No comments :

About the author

My Photo
I trust only simple code and believe that code should be handsome. This is not a matter of technology, but professional approach, consolidated after years of software development. I enjoy to cause things working and feel very happy, when I manage to solve a problem.
Back to Top