import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 文件下载工具类
*/
public class Download {
/**
* 普通java文件下载方法,适用于所有框架
* @param request
* @param res
* @param filePaths 需要打包下载的文件路径集合 路径必须是绝对路径 否则无法下载
* @param zipBasePath 下载文件压缩包之前,必须创建一个空的文件压缩包(下载完成之后删除压缩文件包),zipBasePath 是此文件压缩包所在的文件目录
* @param zipName 下载压缩包的名称
* @return
* @throws IOException
*/
public static String downloadFilesTest(HttpServletRequest request, HttpServletResponse res, List<String> filePaths, String zipBasePath, String zipName) throws IOException {
//将附件中多个文件进行压缩,批量打包下载文件
String zipFilePath = zipBasePath+ File.separator+zipName;
//IO流实现下载的功能
res.setContentType("text/html; charset=UTF-8"); //设置编码字符
res.setContentType("application/octet-stream"); //设置内容类型为下载类型
res.setHeader("Content-disposition", "attachment;filename="+new String(zipName.getBytes(),"iso-8859-1"));//设置下载的文件名称
OutputStream out = res.getOutputStream(); //创建页面返回方式为输出流,会自动弹出下载框
//压缩文件
File zip = new File(zipFilePath);
if (!zip.exists()){
zip.createNewFile();
}
//创建zip文件输出流
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
zipFile(zipBasePath,zipName, zipFilePath,filePaths,zos);
zos.close();
res.setHeader("Content-disposition", "attachment;filename="+new String(zipName.getBytes(),"iso-8859-1"));//设置下载的压缩文件名称
//将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buff = new byte[bis.available()];
bis.read(buff);
bis.close();
out.write(buff);//输出数据文件
out.flush();//释放缓存
out.close();//关闭输出流
return null;
}
/**
* 压缩文件
* @param zipBasePath 临时压缩文件基础路径
* @param zipName 临时压缩文件名称
* @param zipFilePath 临时压缩文件完整路径
* @param filePaths 需要压缩的文件路径集合
* @throws IOException
*/
public static String zipFile(String zipBasePath, String zipName, String zipFilePath, List<String> filePaths, ZipOutputStream zos) throws IOException {
//循环读取文件路径集合,获取每一个文件的路径
for(String filePath : filePaths){
File inputFile = new File(filePath); //根据文件路径创建文件
if(inputFile.exists()) { //判断文件是否存在
if (inputFile.isFile()) { //判断是否属于文件,还是文件夹
//创建输入流读取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
//将文件写入zip内,即将文件进行打包
zos.putNextEntry(new ZipEntry(inputFile.getName()));
//写入文件的方法,同上
int size = 0;
byte[] buffer = new byte[1024*1024]; //设置读取数据缓存大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
//关闭输入输出流
zos.closeEntry();
bis.close();
} else { //如果是文件夹,则使用穷举的方法获取文件,写入zip
try {
File[] files = inputFile.listFiles();
List<String> filePathsTem = new ArrayList<String>();
for (File fileTem:files) {
filePathsTem.add(fileTem.toString());
}
return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem,zos);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return null;
}
}
如有不足之处请在评论中指出。
来源:https://blog.csdn.net/kelly921011/article/details/100079862