由於 JavaScript 本身沒有權限直接操作本機檔案(除非使用 ActiveX,但那既不方便也不安全),因此想從頁面把資料存成檔案是行不通的。换个角度想:表格裡的資料本來就來自伺服器,那麼直接把伺服器端的資料下載成檔案即可。
關鍵是設定正確的輸出路徑標頭,讓瀏覽器以附件形式下載:
ServletOutputStream out = null;
try{
response.setContentType("text/csv");
String disposition = "attachment; fileName=data.csv";
response.setHeader("Content-Disposition", disposition);
out = response.getOutputStream();
byte[] blobData = CSVParser.parseCsv(rs).getBytes();
out.write(blobData);
out.flush();
out.close();
}catch(Exception e){
throw e;
}finally{
if(out != null) out.close();
}
其中 CSVParser.parseCsv(rs) 是一個把資料庫查詢結果 ResultSet 轉換為 CSV 字串的工具類,參數 rs 即為 ResultSet 物件。
前端寫了一個通用函數,只要頁面上有這個函數就能觸發下載,可放到共用的 js 檔中隨處呼叫:
// 帶入 url,根據查詢結果回傳 csv
function bsuExportCsv(url){
if($('#downloadcsv').length <= 0)
$('body').append("<iframe id=\"downloadcsv\" style=\"display:none\"></iframe>");
$('#downloadcsv').attr('src', url);
}
使用時先判斷頁面中是否已有 id 為 downloadcsv 的隱藏 iframe,若沒有就動態加入 body,再把它的 src 設為傳入的 servlet 位址。呼叫方式很簡單:bsuExportCsv("https://localhost:8080/csvservelt"),該位址必須回傳 CSV 格式的資料。