1

I want to create and then download a simple csv file on the client side. When the user click on the open button in the view, it opens the csv file so the user can download it on his PC.

Here's my javascript code :

$("#booksList").on('click', '.export-excel' ,function() {

     var json = { };

    $.ajax({
      type : 'POST',
      data : JSON.stringify(json),
      contentType: 'application/json; charset=utf-8',
      url  : '@routes.BooksController.exportExcel()',
      success: function(data){
         alert('Success');
      },
      error: function(data) {
       alert('Failed to load csv file');
      }
    });
  });

Here's my java code:

 public static Result exportExcel()  {

        String filename = "outFile.csv";

        FileWriter fileWriter = new FileWriter("c:/"+filename+"");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write("This is test line 1.");
        bufferedWriter.newLine();
        bufferedWriter.write("This is test line 2.");

        bufferedWriter.flush();
        bufferedWriter.close();

        return ok(new java.io.File("/tmp/"+filename));
}

My route :

  POST  /app/exportCSV  controllers.BooksController.exportExcel()

But i get a 500 (Internal Server Error) with no details !

What i'm doing wrong ?

user708683
  • 500
  • 3
  • 9
  • 26
  • Are you sure your endpoint is being hit? – robotlos May 12 '16 at 21:02
  • what do you mean ? – user708683 May 12 '16 at 21:03
  • Are you sure your `exportExcel` method is being reached. I'd start with this first. [This link](http://stackoverflow.com/questions/9807382/what-is-a-web-service-endpoint) explains endpoint in a little more detail. – robotlos May 12 '16 at 21:04
  • Yes my exportExcel method is being reached cause when i replace my controller code with only a system.out.print("export reached"); i have no error and i was able to see the "export reached" message. – user708683 May 12 '16 at 21:33
  • I think you need to add some `Exception` catches. Looks like the error is happening while you're processing the `File`. Encapsulate your calls to open and write to the file in a `try/catch`. – robotlos May 12 '16 at 22:23
  • You don't need to write a file to the file system - just put the data in an `InputStream` and use the `ok(java.io.InputStream content)` method to generate the response. This removes another possible bug in your code. – Steve Chaloner May 13 '16 at 07:13
  • Steve : Do you have an example of that ? thanks – user708683 May 13 '16 at 15:46

0 Answers0