2
votes

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()
      )
    );
  }
1
Could it be that it should be "Content-Disposition" and not "Content-disposition"? - johanandren
Still the same response! Maybe I'm not correctly "downloading" the file once the Ajax part succeeds... Thanks though! - FranciscoBouza
Aha, didn't think about the js code, have you tried just setting window.location to the export url (you can get it from the jsroutes-object) instead of calling it with ajax? - johanandren
Yep, tried but no effect :-( Thanks! - FranciscoBouza

1 Answers

2
votes

Well, I realised Javascript was pulling our legs too much, so i decided to do it "Scala Way" like this:

View

@form(routes.User.generateText()){
    <input type="submit" name="commit" value="Export as .txt"> 
}

Controller

response().setContentType("application/x-download");
response().setHeader("Content-disposition", "attachment; filename=test.txt");
return ok(generateTXT(numbers, "test.txt"));

(As i said in my question, generateTXT(String) retrieves a File file)

Thanks!