1、背景
- 要求日志大于5M时,前端不展示日志,改成下载方式下载日志;
- 网上查了,都没给出什么好方法,开始用的是 OutputStream.write() 方法输出文件,但是发现很慢,30+M就花了5Min左右,必须优化;
- 优化方案:a、优化代码;b、使用压缩方式
- 经过考虑后,发现代码优化根本解决不了什么问题,还是从根本出发,用压缩方式下载;
2、下载代码
public static void downloadTaskResult(String result, HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
StringBuilder fileName = new StringBuilder("file.txt");
ZipOutputStream zos = null;
try {
byte[] buffer = result.getBytes();
response.reset();
zos = new ZipOutputStream(response.getOutputStream());
response.setContentType(APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment;filename=" + fileName.toString() + ".zip");
ZipEntry zipEntry = new ZipEntry(fileName.toString());
zos.putNextEntry(zipEntry);
zos.write(buffer);
zos.closeEntry();
zos.flush();
zos.close();
} catch (IOException ex) {
logger.error("Download Task Result error:", ex);
throw new Exception(“error”);
} finally {
if (zos != null) {
try {
zos.close();
} catch (Exception e) {
logger.error("close ZipOutputStream error:", e);
}
}
}
}
3、结论
- 30+M的文件原来下载需要5min,压缩后,只有100+KB,下载只要几秒;
- 有时候,方案还是很重要的;
- 大家有什么好方案可以留言指教,感谢。