服务端zip打包下载

    这几天有一个需求说,一个点击操作,需要产生多个文件的下载,理论上是不可行的。应该一个请求只能有一个响应。所以,考虑把多个文件打包成一个zip包后,再下载。上网搜了一下,可以利用ZipOutputStream类。一开始,什么都不知道,于是随便用的是java.util.zip.ZipOutputStream。后来,发现,尽管产生的文件在服务端没有乱码问题,但是当文件添加到zip包里面后,在客户端下载得到的zip包里面,得到的中文文件名都是乱码。于是在想,换一下编码应该可以吧。试了半天还是不行,又搜了半天,才发现,java.util.zip.ZipOutputStream缺乏编码的转换,中文乱码问题肯定是解决不了的。再搜,发现apache也有一个org.apache.tools.zip.ZipOutputStream,方法声明的什么都一样。于是把类的引用路径改了一下,运行。成功了!!!!

 

mark 一下用法

 1 import org.apache.tools.zip.ZipEntry;
 2 import org.apache.tools.zip.ZipOutputStream;
 3 
 4     String zipfilename = "result.zip";
 5     String zipfilepath = storagePath + zipfilename;
 6     ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipfilepath)));
 7     byte[] buf = new byte[2048];
 8     int len;
 9 
10     String fileName = "我是中文名.txt"; 
11     File file = new File(storagePath + fileName);
12     if(!file.exists()){//文件不存在,创建
13         file.createNewFile();
14     }
15     BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));//指定字符编码
16     bw.write(sb.toString());//往文件中写内容
17     bw.close();
18     
19     ZipEntry ze = new ZipEntry(file.getName());//往zip包写
20     zos.putNextEntry(ze);
21     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
22     while((len = bis.read(buf)) > 0){
23         zos.write(buf, 0, len);
24     }
25     bis.close();
26     zos.closeEntry();
27     zos.close();
View Code

 

posted @ 2013-09-04 10:58  leeshunpeng  阅读(599)  评论(0编辑  收藏  举报