I'm currently working on a project with Play Framework (with Java Controllers) and I'm trying to force browser download of .txt and .xls files after clicking a button and getting information from a controller. Although I form correctly both types of files, I haven't found the way of forcing its download yet.
After hours of deep investigations, I've managed to call the controller by Javascript via JavascriptRoutes and Ajax, but I can't force its download, albeit i could put the .txt content in a div (which loads correctly).
This is what I have now:
function exportText(){
jsRoutes.controllers.User.generateText().ajax({
success: function(data) {
$('#testDiv').html(data);
},
error: function() {
alert("Error!")
}
})
}
(exportText() is called when a button is clicked)
public static Result generateText() {
response().setContentType("application/x-download");
response().setHeader("Content-disposition","attachment; filename=test.txt");
return ok(generateTXT("test.txt"));
}
(generateTXT(String) retrieves a File file)
Any help would be really apreciated! Thanks!
EDIT
the javascriptRoutes method looks like this:
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("jsRoutes",
// Routes
controllers.routes.javascript.User.generateText()
)
);
}
Ajaxpart succeeds... Thanks though! - FranciscoBouza