SpringBoot中實現百度腦圖KM檔案下載
阿新 • • 發佈:2021-01-06
技術標籤:測試開發spring boot
需求背景
將部門樹結構目錄下案例,匯出轉換成本地百度腦圖檔案,實現所有案例本地編輯功能。
實現思路
通過分析百度腦圖生成的本地.km檔案,發現數據格式為JsonString字串格式,使用Map對業務資料進行格式拼裝,最後整體轉成Json格式字串。
實現程式碼
@GetMapping("/exprtNaoTu")
public void exprtNaoTu(@RequestParam("id") Integer id,
HttpServletResponse response) throws UnsupportedEncodingException {
//TODO 省略業務資料拼裝Map程式碼
JSONObject json = new JSONObject(root);
String content = json.toString();
// System.out.println(content);
String fileName = StringUtils.join(names, "_") + ".km";
// 清空response
response. reset();
// 設定response的Header
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下載檔案能正常顯示中文
response.setHeader ("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
try {
OutputStream os = response.getOutputStream();
os.write(content.getBytes(StandardCharsets.UTF_8));
os.close();
} catch (IOException e) {
e.printStackTrace();
log.error("檔案下載失敗", e);
}
}
遇到的坑
前端頁面點選下載後,程式碼不提示異常,頁面也不提示下載檔案,或者直接相應返回資料,需求修改前端或者JS程式碼
<li style="height:24px;"><a id="exprtNaoTu" th:href="@{/jrcsptcase/exprtNaoTu(id=${menuId})}">腦圖</a></li>
window.location.href="XXX/XXX/XXXX";