0

I want to write some data to a csv file and user should be able to download it through browser.

@Actions({ @Action(value = "/downloadReport", results = { @Result(name = "success", type = "stream", params = {
    "contentType", "${type}", "inputName", "stream", "bufferSize","2048", "contentDisposition",   
    "attachment;filename=\"${filename}\"" }) }) })
@SkipValidation
public String downloadReport() throws BaseAppException {

     try {
            filename =AdSkippingConstants.REPORT_FILE_NAME;
            type = AdSkippingConstants.CSV_FILE_TYPE;
            File file = new File(filename);
            FileUtils.write(file, "Helloo World");
            stream = new FileInputStream(file);
        } 
        catch (IOException e) {
        logger.error("Error occured while exporting error data", e);
        } 
        return SUCCESS;
       }

In jsp i am using ajax call

    function exportAsCSV(){
      $.ajax({
      url: 'downloadReport.action?',
      type: "POST",
       success: function() {
        //To Un Block the Change Password page if the page reloaded
          //$('div.ui-dialog').unblock();
         // $('#change_password_details_body').html(data);
      },
      error: function(){
        //To Un Block the Change Password page if the page reloaded with error.
          //$('div.ui-dialog').unblock();
      }
});
}

I am able to get the response and even fileDownload=true is coming in response but still download to csv option is not opening in any browser and also please let me know how to pass html data to action for writing to csv.

In jsp i am using this code to do ajax call

var gridModel = "gridModel";
var sortname = "1";
var sortorder = "asc";
var caption = '<s:text name="grid.label.heading" />';
var url = "getGridSearchResults.action";
init.push(function() {
    loadTable("gridtable", url, gridModel, columnDefs, columns, sortname,
            sortorder, caption);
});

 <table cellpadding="0" cellspacing="0" border="0"  class="table table-   striped table-bordered" id="gridtable"></table>   

So with ajax call i am loading the data for the table.

Pracheer Pancholi
  • 570
  • 2
  • 7
  • 21

2 Answers2

1

You don't need AJAX. This is a common misconception.

You simply need to perform a call to an action returning a stream result, with a contentDisposition: attachment HTTP header.

This will tell the browser to download the file instead of opening it inline.

Read more in this answer


EDIT: if you need to send data from an HTML table to the action, you need to

  • use hidden input fields having the same value that you printed with <s:property/> tags (or whatever);
  • specify an index with the list[%{#status.index}].attribute notations to post the different records as different elements of a Collection.
Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Thanks for the reply Andrea this resolves first issue but how to pass html table data to the action for writing data to csv . I have bootstrap table which is loaded with data i want to write that data into csv and download that but how to pass the data to action. – Pracheer Pancholi Jun 12 '15 at 09:08
  • Andrea i am using ajax call to prepare data for the table grid here i am not using s:property to display the data in the cell so if the grid is loaded is there any way i can get the grid data and pass to – Pracheer Pancholi Jun 12 '15 at 09:38
  • Yes but why are you using AJAX ???? It is not needed here. BTW it's the same: create hidden inputs, then read them with javascript, then send them with AJAX – Andrea Ligios Jun 12 '15 at 09:44
  • The data is there in some server which i need to hit and populate it in grid that's why i am using ajax to hit the action and that action in turns retrieve the data and using that data i am inserting that into the grid .. that's why here i was using – Pracheer Pancholi Jun 12 '15 at 09:51
  • You don't need AJAX to hit a server. An action loads data server-side no matter if it is called through AJAX or standard submit. AJAX makes the difference when you want to post data or load data in the same page; it is absolutely irrelevant when you are DOWNLOADING A FILE. The whole question makes no sense, it smells of [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) from KMs, but if you feel it's right this way, then edit the question and try to be CRYSTAL CLEAR about what you've done and what you want to do, by also adding some minimal, relevant code ... – Andrea Ligios Jun 12 '15 at 09:56
  • Andreas i have modified the code please have a look into that and let me know way of passing this table data as a parameter to – Pracheer Pancholi Jun 12 '15 at 10:08
  • 1) I'm Andrea 2) Read this http://tinyurl.com/stack-hints **entirely** 3) take your time to rewrite the question from scratch, as if you were writing the text of an exam for your students. Up to then, I'm voting to close this as *not clear what you're asking*. – Andrea Ligios Jun 12 '15 at 12:01
  • Andrea my question was not that complex just i want to know how to get download as csv enabled and passing the table grid data to the action class for writing and downloading to csv. Earlier i was using ajax call to call the action for download but then i removed it and used – Pracheer Pancholi Jun 12 '15 at 12:30
  • The amount of details is not the solution, but the first problem, since they cause noise and lower the noise-to-signal ratio. The few, relevant details are better than a massive amout of them; By the way IF you are not using AJAX anymore, and are using – Andrea Ligios Jun 12 '15 at 12:41
  • 1
    Thanks Andrea for the suggestion i am not taking that as an attacking mode surely i will take your implement that. – Pracheer Pancholi Jun 12 '15 at 13:11
0

I have done it using :

ActionContext.getContext().getSession().put("RESULTS_GRID", searchResultsForDownload);

and then retrieving the list in my DownLoadAction for getting the data and writing to csv using BufferedWriter.

Pracheer Pancholi
  • 570
  • 2
  • 7
  • 21