后端
1、拿到数组id
2、拿到要批量下载的路径
3、读取要批量下载的路径,写入临时路径
4、下载临时路径目录下所有文件
5、删除临时路径
@RequestMapping(value="/downloadMany.ajax")
public void downloadMany(T9c_employee_papersDTO t9c_employee_papersDTO,HttpServletRequest request,HttpServletResponse response) throws IOException{
request.setCharacterEncoding("UTF-8");
OutputStream fileOut = null ;
//拿到数组id
String[] ids = t9c_employee_papersDTO.getSel();
String tempZipname = "";
String filepath ="";
String temp_path="";
for(String id : ids) {
t9c_employee_papersDTO.setId(id);
if(!StringUtils.isEmpty(id)){//交付阶段压缩包
//拿到该证件的整条信息
t9c_employee_papersDTO=t9c_employee_papersService.getT9c_employee_papaersById(t9c_employee_papersDTO);
//路径信息
filepath=t9c_employee_papersDTO.getAddress();
//临时路径,papers替换papers/temp/userid+姓名
temp_path=filepath.replace("papers", "papers/temp/"+t9c_employee_papersDTO.getUserid()+t9c_employee_papersDTO.getUsername());
//截取temp后的路径,图片之前的路径
String temp_dir = temp_path.substring(0,temp_path.lastIndexOf("\\"));
//创建temp临时路径
File dir = new File(temp_dir);
if(!dir.exists()) {
dir.mkdirs();
}
//把文件放入路径之下
File file=new File(temp_path);
if(!file.exists()) {
file.createNewFile();
}
//路径下文件为输出流
fileOut = new FileOutputStream(file);
//定义输入流
InputStream inp=null;
try {
//读取路径下文件,输出流写入
inp = new FileInputStream(filepath);
byte[] bytes = new byte[4096];
int length;
while ((length = inp.read(bytes)) > 0){
fileOut.write(bytes, 0, length);
}
} finally {
if(null != inp){
inp.close();
fileOut.close();
}
}
}
}
try {
tempZipname="certificaty_info.ZIP";//压缩文件名
ZipUtils zipUtils = new ZipUtils();
//获得压缩到哪个路径
String s=temp_path.substring(0,temp_path.indexOf("temp")+4);
zipUtils.zip(tempZipname, s, response);
File file =new File(s);
deleteFile(file);
}catch (Exception e) {
logger.info(e.getMessage());
}
}
递归删除临时目录
public static void deleteFile(File file) {
if(file.exists()) {//判断路径是否存在
if(file.isFile()){//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
file.delete();
}else{//不是文件,对于文件夹的操作
//保存 路径D:/1/新建文件夹2 下的所有的文件和文件夹到listFiles数组中
File[] listFiles = file.listFiles();//listFiles方法:返回file路径下所有文件和文件夹的绝对路径
for (File file2 : listFiles) {
/*
* 递归作用:由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
* 注意:此时的文件夹在上一步的操作之后,里面的文件内容已全部删除
* 所以每一层的文件夹都是空的 ==》最后就可以直接删除了
*/
deleteFile(file2);
}
}
file.delete();
}else {
System.out.println("该file路径不存在!!");
}
}