系統日志的獲取不可能每次都登錄服務器,所以在頁面上能夠下載系統運行的日志是必須的
如何來實現日志的下載,這樣的一個功能
?前端我們用到的是window.open(...)這樣可以發送一個get請求到后臺
?后臺接收到get請求之后,如何實現對文件的下載
@ResponseBody@RequestMapping("downlogsfile")public void downlogsfile(HttpServletResponse response,String filename) throws IOException {logger.info("**************下載日志相關的日志信息{}*****************",filename);response.setCharacterEncoding("UTF-8");response.setContentType("text/plain;charset=GBK");String path =configService.getByConfigValueByName("LOGPATH");String filepath = path + "/" + filename;logger.info(filepath);File file = new File(filepath);if (file.exists()) {logger.info("找到相關的日志文件:{}", filepath);DownLoadUtils.downloadtxt(response, file);} else {logger.info("文件不存在");}}
關鍵是DownLoadUtils.downloadtxt(response, file);
public static void downloadtxt(HttpServletResponse res,File file) throws IOException {long length = file.length();res.addHeader("Content-Length", String.valueOf(length));res.addHeader("Content-Type","text/plain; charset=utf-8");res.setHeader("Content-Disposition","attachment;filename="+file.getName());OutputStream outputStream = res.getOutputStream();byte[] buff = new byte[1024];BufferedInputStream bis = null;FileInputStream fileInputStream=new FileInputStream(file);bis = new BufferedInputStream(fileInputStream);int i = bis.read(buff);while (i != -1) {outputStream.write(buff, 0, buff.length);outputStream.flush();i = bis.read(buff);}bis.close();fileInputStream.close();outputStream.close();}
這個里面res.setHeader很重要
res.addHeader("Content-Type","text/plain; charset=utf-8");
text/plain? 純文本的格式,并且設置編碼
res.setHeader("Content-Disposition","attachment;filename="+file.getName());
"Content-Disposition","attachment;filename="+file.getName()
實現下載