java 打包边下载_JAVA实现边下载边压缩

@ResponseBodypublic voiddownloadUrl(HttpServletResponse response, HttpServletRequest request){

String sourceFilePath=properties.getString("sourceFilePath");//要下载的文件路径

eavlProName = xxx;//项目名

String downloadName = "xxx.zip"; //下载文件名

String agent = request.getHeader("USER-AGENT"); //浏览器内核信息

try{if (agent.contains("MSIE")||agent.contains("Trident")) {//IE

downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");

}else{

downloadName= new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");

}

}catch(Exception e) {

e.printStackTrace();

}

zip(sourceFilePath, eavlProName, response, downloadName);

response.getOutputStream().close();//这个应该没什么用

}private voidzip(String souceFileName, String eavlProName, HttpServletResponse response, String downloadName) {

File file= newFile(souceFileName);try{

zip(file, eavlProName, response, downloadName);

}catch(IOException e) {

e.printStackTrace();

}

}private void zip(File souceFile, String eavlProName, HttpServletResponse response, String downloadName) throwsIOException {

ZipOutputStream out= null;//设置压缩流。

response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");try{

out= new ZipOutputStream(newBufferedOutputStream(response.getOutputStream()));

out.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法

} catch(Exception e) {

e.printStackTrace();

}

out.setEncoding("gbk");

zip(souceFile, out, eavlProName, eavlProName,null);

out.closeEntry();

out.close();

}private voidzip(File souceFile, ZipOutputStream out, String base, String eavlProName, Integer i)throwsIOException {if(souceFile.isDirectory()) {

File[] files=souceFile.listFiles();if (files.length != 0) {if (i == null || i != 1) { //对于地方目录先不创建,当地方目录下存在项目的截图时,才创建

out.putNextEntry(new ZipEntry(base + "/"));

base= base.length() == 0 ? "" : base + "/";

}if (i == null) {

i= 0;

}

i++;for(File file : files) {if (i == null || i != 2) { //2地方下面的项目名.这种不创建目录

zip(file, out, base +file.getName(), eavlProName, i);

}else{

String picPathname=file.getName();if (picPathname.equals(eavlProName)) { //取对应项目下的文件

zip(file, out, base, eavlProName, i);

}

}

}

}

}else{if (base.length() > 0) {

out.putNextEntry(newZipEntry(base));

}else{

out.putNextEntry(newZipEntry(souceFile.getName()));

}

FileInputStream in= newFileInputStream(souceFile);intb;byte[] by = new byte[1024];while ((b = in.read(by)) != -1) {

out.write(by,0, b);

}

in.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值