返回信息流public static void downloadAll(ChmMethod chmMethod,List<File> files){
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("downloadAll chmMethod:"+chmMethod);
try {
/**这个集合就是你想要打包的所有文件,
* 这里假设已经准备好了所要打包的文件*/
double a = Math.random()*100;
a = Math.ceil(a);
int randomNum = new Double(a).intValue(); //下載的文件名是檢測方法名再加隨機數
String downfilename = chmMethod.getName().replaceAll("/","")+"_"+
randomNum+".rar";
File file = new File(downfilename);
System.out.println("file:"+file);
if (!file.exists()) {
file.createNewFile();
}
response.addHeader("Content-Disposition", "attachment; filename="
+ new String(file.getName().getBytes("gb2312"), "iso-8859-1"));
response.setContentType("application/octet-stream");
//创建文件输出流
response.reset();
System.out.println(file.getName());
FileOutputStream fous = new FileOutputStream(file);
// OutputStream os = new BufferedOutputStream(fous);
// CheckedOutputStream csum = new CheckedOutputStream(fous,new Adler32());
// OutputStream os = new BufferedOutputStream(new FileOutputStream("a.zip" ));
ZipOutputStream zipOut = new ZipOutputStream(fous);
// ZipOutputStream zipOut = new ZipOutputStream(os);
/**这个方法接受的就是一个所要打包文件的集合,
* 还有一个ZipOutputStream*/
zipOut.setEncoding("gbk");
DownLoad.zipFile(files, zipOut);
zipOut.close();
// fous.close();
/**直到文件的打包已经成功了,
* 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中,
* 稍后会呈现出来,接下来的就是往客户端写数据了*/
OutputStream out = response.getOutputStream();
// OutputStream out = getResponse().getOutputStream();
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buf = new byte[1024];
int len = 0;
while((len = bin.read(buf)) > 0)
out.write(buf,0,len);
out.close();
bin.close();
/**最后的操作是把创建的临时文件删除*/
try {
File f = new File(file.getPath());
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
这是一条镜像帖。来源:北邮人论坛 / java / #24308同步于 2013/2/20
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
Re: 文件打包下载error
Wallcott
2013/2/20镜像同步1 回复
订阅后,新回复会通过你的通知中心匿名送达。
1 条回复
【 在 Wallcott 的大作中提到: 】
: : public static void downloadAll(ChmMethod chmMethod,List<File> files){
: HttpServletResponse response = ServletActionContext.getResponse();
: ...................
[code=java]
/*我去,这代码效果不错啊*/