Java 批量下载成压缩包

今天有个需求 就是将选中的文件批量下载成压缩包。记录贴

先将文件通过流放入压缩包

//先new一个文件文件名字随意
File zipFile = new File("D:/"+str+".zip");
byte[] buf = new byte[1024];
int len;
//在服务器端生成压缩文件包,然后通过压缩流将压缩包流化。
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));
try {
if(fileIds!=null && fileIds.length>0){	
//我是根据fileid查询文件,而文件是通过二进制存入数据库
for(String fileId : fileIds){
//这个model里面有文件src之类的。具体下面会说到
FileModel fileModel = attachmentManageService.loadFileModelByFileId(fileId);
//获取数据库里的二进制数据放入buffer
byte[] buffer = fileModel.getFileBytes();
//zipEntry 是将文件压缩的方法。然后putNextEntry是打开刚才的压缩文件吧。zont相当于流化的对象
zout.putNextEntry(new ZipEntry(fileModel.getFileName()));  
//将刚才的文件写入压缩包
zout.write(buffer);  
//关闭压缩包
zout.closeEntry();   
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭压缩对象流
zout.close();
}
        

下面就是用户下载刚才的压缩包。弹出另存为下载

//接刚才的代码。这个是读取服务器上生成的压缩包的文件放入流
FileInputStream zipInput =new FileInputStream(zipFile);
//输出流获取response里的对象
OutputStream out = new BufferedOutputStream(response.getOutputStream());
//设置传输的类型,文件类型,可以弹出另存为。其他的type没研究过
response.setContentType("multipart/form-data"); 
//设置头下载的文件名自定义和程序无关,就是下载的文件的名字提用户先起好的压缩包名
response.setHeader("Content-Disposition", "attachment; filename="+zipFile.getName());
try {
//输出
while ((len=zipInput.read(buf))!= -1){  
out.write(buf,0,len);  
}
} catch (Exception e) {
e.printStackTrace();
}finally {
zipInput.close();
out.flush();
out.close();
}
//用户下载完成后。删除服务器端的压缩文件。
zipFile.delete();

主要就是给用户压缩的过程。

猜你喜欢

转载自blog.csdn.net/zdreamLife/article/details/81744699