您的位置:首页 > 编程语言 > Java开发

Struts2多文件zip打包下载

2017-11-16 18:12 375 查看
我们团队在做一个项目,其中的一个功能是jsp页面点击“一键下载”,属于同一个活动的所有文件就可以在后台打包为一个zip文件,在前台直接下载一个zip文件就可以,zip文件解压后就会是文件夹里许多这类的文件。

核心jar包:commons-compress

在程序中导入压缩文件所需要的jar包:jar包下载

正文来了

多文件打包下载的重点在于如何将文件进行打包。在项目中体现的流程便是:获取待下载的文件路径->添加进zip文件->返回zip路径->zip文件下载。 

我们一步一步来: 

在之前的项目中我们将待下载的文件路径储存在了session中的downloadFileList中,再获取所有的文件指针,并传入压缩方法中,代码如下:
public String downloadMultiFile() {
//使用默认文件名称
String name = "1501-实验报告.zip";
//压缩后的zip文件存放路径
fileName = ServletActionContext.getServletContext().getRealPath("/WEB-INF/download")+File.separator+name;
System.out.println("压缩文件路径:"+fileName);
//获取打包下载的路径
Map<String, ResourceFile> downloadFiles = (Map<String, ResourceFile>) ServletActionContext.getRequest().getSession().getAttribute("downloadFileList");
ArrayList<String> downloadFilePath = new ArrayList<>();
for (String key : downloadFiles.keySet()) {
System.out.println("待下载文件:"+downloadFiles.get(key).getFilePath());
downloadFilePath.add(downloadFiles.get(key).getFilePath());
}
//将多个附件的路径取出
if(downloadFilePath.size() > 0) {
File[] files = new File[downloadFilePath.size()];
for(int i=0;i<downloadFilePath.size();i++) {
if(downloadFilePath.get(i) != null) {
String filepath =ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload")+File.separator+downloadFilePath.get(i).trim().replace("/","\\");

File file = new File(filepath);//获取到文件指针
if(file.exists()) {
System.out.println("获取文件指针---"+filepath+"---成功");
files[i] = file;
}
}
}
//将多个附件压缩成zip到指定路径
System.out.println("开始压缩文件....");
ZipFileUtil.compressFiles2Zip(files,fileName);
}
fileName = name;//zip文件名称,zip下载的action中有前面省略的路径,可自行更改
return SUCCESS;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

多文件下载action的配置文件如下:压缩完文件之后便转发到下载action中,参数为zip文件的路径。注意路径的转换
<action name="mulDownload" class="action.MulFileDownloadAction" method="downloadMultiFile">
<result name="success" type="redirectAction">
<param name="actionName">zipDownload</param>
<param name="fileName">${fileName}</param>
</result>
</action>
1
2
3
4
5
6

zip下载的action只是修改了一点内容(获取文件名时这里使用的是file.substring(file.lastIndexOf(“\\”)+1)),配置与上一篇文章类似,只需要修改类名和name:
public InputStream getInputStream() throws UnsupportedEncodingException, FileNotFoundException {
System.out.println("获取zip输出流");
String filepath =ServletActionContext.getServletContext().getRealPath("/WEB-INF/download")+File.separator;
String file = filepath+fileName;
System.out.println(file);
setDownloadFileName(new String(file.substring(file.lastIndexOf("\\")+1).getBytes(),"ISO8859-1"));//这里需要设置编码格式,因为配置文件的编码为ISO8859-1
return new BufferedInputStream(new FileInputStream(file));
}
1
2
3
4
5
6
7
8

这里是ZipFileUtil类源代码:
package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

/**
* Created by zipple on 2017/10/11.
*/
public class ZipFileUtil {
/**
* 把文件压缩成zip格式
* @param files         需要压缩的文件
* @param zipFilePath 压缩后的zip文件路径   ,如"D:/test/aa.zip";
*/
public static void compressFiles2Zip(File[] files, String zipFilePath) {
if(files != null && files.length >0) {
if (isEndsWithZip(zipFilePath)) {
ZipArchiveOutputStream zaos = null;
try {
File zipFile = new File(zipFilePath);
zaos = new ZipArchiveOutputStream(zipFile);
zaos.setUseZip64(Zip64Mode.AsNeeded);

//将每个文件用ZipArchiveEntry封装,再用ZipArchiveOutputStream写到压缩文件中
for (File file : files) {
System.out.println("压缩...");
if (file != null) {
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName());
zaos.putArchiveEntry(zipArchiveEntry);
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024 * 5];
int len = -1;
while ((len = is.read(buffer)) != -1) {
//把缓冲区的字节写入到ZipArchiveEntry
zaos.write(buffer, 0, len);
}
//Writes all necessary data for this entry.
zaos.closeArchiveEntry();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (is != null)
is.close();
}

}
}
zaos.finish();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (zaos != null) {
zaos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

}
System.out.println("文件压缩完成w.");
}

}

/**
* 判断文件名是否以.zip为后缀
* @param fileName        需要判断的文件名
* @return 是zip文件返回true,否则返回false
*/
public static boolean isEndsWithZip(String fileName) {
boolean flag = false;
if(fileName != null && !"".equals(fileName.trim())) {
if(fileName.endsWith(".ZIP")||fileName.endsWith(".zip")){
flag = true;
}
}
return flag;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2.0