Reputation: 179
I have an export method to get a CSV of all items in a MongoDB collection. I use Apache Commons CSV jar. If I comment out the response() it gives me a no file, but if I include the response(), it will download the CSV on load of the page where my export button is. Also, it'll download the HTML code generated by the view template. However, the CSV is generated as it is in my play directory (and correct) on the server-side.
<a target="_blank" class="btn btn-success" href="@controllers.Application.export" download="Masterlist.csv">Export Domains</a>
public static Result export(){
File fi = new File("Masterlist.csv");
try{
CSVPrinter printer = new CSVPrinter(new FileWriter(fi), CSVFormat.TDF);
//creates the header for the CSV
//creates each line of the CSV
printer.close();
}catch(IOException e){
e.printStackTrace();;
}
//response().setContentType("application/x-download");
//response().setHeader("Content-disposition", "attachment; filename=OLP_Masterlist.csv");
return ok(fi);
}
EDIT: Using Play Framework 2.2.1
Upvotes: 0
Views: 467
Reputation: 11274
The second header should be set automatically. To set the filename, use return ok(fi, "OLP_Masterlist.csv" );
.
In your hyperlink, you shouldn't refer to the controller directly, but use @routes.Application.export
. By using the route, you will generate the correct link. When you refer to the method directly, you are executing when loading the page.
Upvotes: 1