2012-08-23 79 views
2

編輯使用Play下載.csv!框架

從我已經學會(由nico_ekito評論)這是不可能使用AJAX調用來下載文件。解決方法是創建一個隱藏的,它將下載文件,描述爲here


問題: 瀏覽器不顯示下載對話框。任何瀏覽器 - ff,opera,chrome,safari,即。

我讀了docs關於充當文件,發現this question,並在此基礎上,寫道:

Controller.response().setContentType("text/csv"); 
Controller.response().setHeader("Content-Disposition", "attachment;filename=public/export/filename.csv"); 
Controller.response().setHeader("Cache-control", "private"); 

return ok(CSV.export(data, filename)); 

CSV是一類:

public class CSV{ 
    public static File export(Map<String, String> data, String filename){ 
     String csv = data.get("data[saveMe]"); 

     try { 
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("public/export/" + filename), "UTF-8")); 
      bw.write(csv); 
      bw.newLine(); 
      bw.flush(); 
      bw.close(); 
     }catch(UnsupportedEncodingException e){} 
     catch(FileNotFoundException e){} 
     catch(IOException e){} 

     File downloadMe = new File("public/export/" + filename); 

     return downloadMe; 
    } 
} 

在客戶端,我用dojo來發送POST請求(我也試過GET,結果是一樣的):

xhr.post({ 
    url: '/exportData/', 
    content: { 
     saveMe: str 
    } 
}).then(function(response){ 
    //do sth 
}); 

響應頭看起來像:在Firebug

Cache-Control  private 
Content-Disposition attachment;filename=public/export/filename.csv 
Content-Type  text/csv 
Transfer-Encoding chunked 

POST標籤顯示在適當的csv格式正確的數據。要格式化用CSV風格的數據我用dojox/grid/enhanced/plugins/exporter/CSVWriter

+0

您是否嘗試過使用GET請求而不是POST? – Davz

+0

感謝您的輸入,但'GET'不起作用 – maialithar

+0

爲什麼使用Ajax而不是通過HTML鏈接進行簡單的GET? –

回答

3

我想是不是可以從一個Ajax請求下載一個文件,看到了這個問題:Allow User to Download File using Ajax

您應該使用iframe作爲問題提出,或使用包含您的數據的標準HTML表單,並在此表單上發佈帖子。

+0

'dojo.io.iframe'在這種情況下是正確的解決方案,如[本問題]中所述(http://stackoverflow.com/questions/4570559/dojo-io-iframe-and-download-of-excel- PDF)。 – maialithar

+0

感謝您的反饋! –