kenp
kenp

Reputation: 500

Play Framework : Sending CSV file as an attachment

How to send a CSV file as an attachment in Play framework? I looked into the Play documentation by I didn't find what I'm looking for. I know I can return an input stream like that : ok(java.io.InputStream content, int chunkSize) but how to create and send the content to the csv file?

Upvotes: 0

Views: 1642

Answers (3)

asch
asch

Reputation: 1963

Play makes it easy to manipulate a HTTPResponse. You can find in the manual, how to add headers, set cookies etc. in a response.
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");
}  

Upvotes: 1

marcospereira
marcospereira

Reputation: 12212

PlayFramework already have a method to delivery files as attachments (see Results.ok too). Just do the following:

public Result deliveryFile() {
    File file = ...
    boolean inline = true;
    return ok(file, inline);
}

Keep in mind that is up to you to ensure the file exists and is readable.

Upvotes: 0

Kevin
Kevin

Reputation: 1523

Sounds like you're looking to do something like this:

 public Result downloadCsv() {
    response().setHeader("Content-disposition", "attachment; filename=example.csv");
    return ok(Play.application().getFile("conf/resources/example.csv"));
}

Upvotes: 0

Related Questions