Send file to user using views

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).

  1. 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)
  2. After this, you need to create a folder with the same name of the controller (in this case: MyController) – app/views/MyController
  3. Now in the controller, you’ve to create an index method, where you’ll output data for the user, for instance:
    1. public static void index() {
          List users = User.all().fetch();
          render(users);
      }
    2. 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();
      }
  4. 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 .

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • FriendFeed
  • LinkedIn
  • MySpace
  • Twitter
This entry was posted in Internet, play, Software Development and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>