There are some simple steps to send a file to the user of your web application using the Play Framework:
1. After the controller is created (what I do is to copy the controller “Application” and do a refactor rename to the name I want).
- Create a file named MyController (what I do is to copy the controller “Application” and do a rename to the name I want – in this case i chose the name MyController)
- After this, you need to create a folder with the same name of the controller (in this case: MyController) – app/views/MyController
- Now in the controller, you’ve to create an index method, where you’ll output data for the user, for instance:
-
public static void index() { List users = User.all().fetch(); render(users); } - Now you need to create a method that will create the file, or get the file somewhere:
public static void generateMyDocument() { File f = new File("myFile.xls"); //now you've to edit the file, in this is case is an excel file, //so you can edit using a library like JExcelAPI//set the header with the size of the file response.setHeader("Content-Length", String.valueOf(f.length())); //set the content type, in this case is a microsoft excel response.contentType = "application/ms-excel"; //send the file to the user renderBinary(f); //after I send the file, I want to return to the same page (index()) index(); }
-
- Now we need to create a view, inside that folder we just created (create an index.html file):
-
<a href="@{generateMyDocument()}">Download file</a>We are calling the method from the controller. First we have the folder with the same name that will route directly to the method of the controller.Off course that we could do this:
<a href="@{MyController.generateMyDocument()}">Download file</a>And that’s it. The magic on the Play Framework is done .
-
This rule says that 80% of your outcomes come from 20% of your inputs. For instance, in your life, there are certain activities that you do (your 20%) that account for the majority (your 80%) of your happiness and outputs.
