如何将要下载文件在下载前压缩

52 篇文章 0 订阅
25 篇文章 0 订阅

在web application中,有时需要查看log4j产生的log文本文件,在网络速度有限时,在下载log文件前将其读入内存并转化成压缩内容直接下载,不但速度快,而且不用在服务器上硬盘产生压缩文件,具体代码如下jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@page import="java.io.*"%>
<%@page import="java.util.zip.*"%>
<%@page import="java.util.*"%>
<%
 String filename = request.getParameter("filename");
 String selfPath = this.getServletContext().getRealPath("/");
 selfPath=selfPath+File.separator+"logs";
 String filepath = selfPath+File.separator+filename;
 OutputStream outputStream = response.getOutputStream();
 InputStream inputStream = new FileInputStream(filepath);
 int filelength =inputStream.available() ;
 
 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(  );
 InputStream is = new FileInputStream(filepath);

 
 ZipEntry entry = new ZipEntry(filename);
 ZipOutputStream zos = new ZipOutputStream(  byteOutputStream );
 zos.putNextEntry(entry);
 byte[] buffer = new byte[1024];
 int i = -1;
 while ((i = inputStream.read( buffer)) != -1) {
     zos.write(buffer, 0, i);
 }
 inputStream.close();
 zos.close();
 
 String fileminitype="application/x-download";
 response.setContentType(fileminitype);
 response.setHeader("Content-Disposition", "attachment; filename=" + filename+".zip");
 response.setContentLength( byteOutputStream.size() );
 
 outputStream.write(   byteOutputStream.toByteArray() );
 byteOutputStream.close();
 outputStream.close();
%>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值