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.
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 acontentDisposition: 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
<s:property/>
tags (or whatever);list[%{#status.index}].attribute
notations to post the different records as different elements of a Collection.