Search code examples
javacsvplayframework

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?


Solution

  • 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");
    }