一:批量文件打包下载详细代码解析
多文件打包下载的重点在于如何将文件进行打包。在项目中体现的流程便是:获取待下载的文件路径->添加进zip文件->返回zip路径->zip文件下载。
我们一步一步来:
在程序中导入压缩文件所需要的jar包:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
public String downloadMultiFile() throws IOException {
//获取将要下载的文件路径
String urls = this.getHttpServletRequest().getParameter("attachment");
String[] files = urls.split(",");
// String[] files = {"/2018-08/84d378c9-6eb4-41c5-b16a-87538603b327_菲律宾邀请函.doc","/2018-08/f3f86879-dbd2-4b18-aa75-74135ab4bd48_打表测试.docx"};
//使用默认文件名称
String name = "文件压缩包.zip";
//压缩后的zip文件存放路径
//使用File.separator代替"\\",避免Linux系统解析成/
String fileName = "C:"+File.separator+"uploadMeterial"+File.separator+name+"";
System.out.println("压缩文件路径:"+fileName);
//获取打包下载的路径
File[] filestr = new File[files.length];
for(int i = 0;i<files.length;i++){
if(files[i] != null){
String filepath = "C:"+File.separator+"uploadMeterial"+files[i];
File file = new File(filepath);//获取到文件指针
if(file.exists()) {
System.out.println("获取文件指针---"+filepath+"---成功");
filestr[i] = file;
}
}
}
//将多个附件压缩成zip到指定路径
System.out.println("开始压缩文件....");
ZipFileUtil.compressFiles2Zip(filestr,fileName);
fileDownloads(fileName);
//fileName = name;//zip文件名称,zip下载的action中有前面省略的路径,可自行更改
return SUCCESS;
}
public String fileDownloads(String fileName) throws IOException {
HttpServletResponse response = this.getHttpServletResponse();
String fileSaveRootPath = fileName;
//得到要下载的文件
File file = new File(fileSaveRootPath);
//如果文件不存在
if(!file.exists()){
resultList.put("status",210);
resultList.put("failMesg","您要下载的资源已被删除");
return SUCCESS;
}
fileName = "材料打包文件.zip";
//设置响应头,控制浏览器下载该文件
this.getHttpServletResponse().reset();
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(fileSaveRootPath);
//创建输出流
OutputStream out = response.getOutputStream();
//创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区当中
while((len=in.read(buffer))>0){
//输出缓冲区的内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
//关闭文件输入流
in.close();
//关闭输出流
out.close();
resultList.put("status",200);
return SUCCESS;
}
这里是ZipFileUtil类源代码:
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;
}
}
借鉴该篇文章:https://blog.csdn.net/csu_passer/article/details/78202518