系统日志的获取不可能每次都登录服务器,所以在页面上能够下载系统运行的日志是必须的
如何来实现日志的下载,这样的一个功能
前端我们用到的是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()
实现下载