從我已經學會(由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
您是否嘗試過使用GET請求而不是POST? – Davz
感謝您的輸入,但'GET'不起作用 – maialithar
爲什麼使用Ajax而不是通過HTML鏈接進行簡單的GET? –