2015-06-12 73 views
0

我想將一些數據寫入csv文件,用戶應該可以通過瀏覽器下載。使用struts 2作爲csv下載

@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; 
     } 

在JSP中我使用Ajax調用

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(); 
     } 
}); 
} 

我能得到響應,甚至fileDownload =真正的響應來,但還是下載到CSV選項未在任何瀏覽器中打開和也請讓我知道如何通過html數據寫入csv的行動。

在JSP中我使用這個代碼做Ajax調用

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> 

因此,與Ajax調用我加載的數據表。

+0

但是它是Ajax,沒有對話框會彈出標準的Ajax調用。 –

+0

那麼我該如何在jsp中調用動作並獲取下載作爲csv工作 –

+0

@PracheerPancholi您是否在所有瀏覽器或只有IE瀏覽器中都有此問題? –

回答

1

你不需要AJAX。這是一個普遍的誤解。

您只需調用返回stream結果的操作,並使用contentDisposition: attachment HTTP標頭。

這將告訴瀏覽器下載文件,而不是打開它的內聯。

Read more in this answer


編輯:如果你需要從一個HTML表發送數據的動作,你需要

  • use hidden input fields有你印有<s:property/>標籤相同的值(或隨你);
  • specify an indexlist[%{#status.index}].attribute表示法將不同記錄作爲集合的不同元素髮布。
+0

感謝您的回覆Andrea解決了第一個問題,但是如何將html表數據傳遞給將數據寫入csv的操作。我有bootstrap表,它載入數據,我想把這些數據寫入csv並下載,但是如何將數據傳遞給action。 –

+0

Andrea我正在使用ajax調用爲表格網格準備數據,這裏我沒有使用s:property來顯示單元格中的數據,所以如果網格被加載有任何方法我可以獲取網格數據並傳遞給

+0

是的,但你爲什麼使用AJAX?這裏不需要。順便說一句:創建隱藏的輸入,然後用javascript讀取它們,然後用AJAX發送它們 –

0

我已經使用了這事

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

,然後檢索在我DOWNLOADACTION用於獲取數據,並使用BufferedWriter將寫入CSV列表。