java后台批量下载文件压缩ZIP
public String do_downloadFiles() throws Exception {
String entityId = getRequestParameter("entity.id");
String path = ServletActionContext.getServletContext().getRealPath(SysUtils.getSysParam("storageDIR", "/upload"));
List<ProjectApplyBook> projectApplyBookList = bo.getProjectApplyInfoById(entityId);
List<String> filePaths = new ArrayList<String>();
List<String> uploadFileNames = new ArrayList<String>();
for (ProjectApplyBook projectApplyBook : projectApplyBookList) {
String applierId = projectApplyBook.getApplierId();
List<Person> personList = bo.getPersonById(applierId);
String fileId = projectApplyBook.getFileId();
if(fileId != null){
String[] ids = projectApplyBook.getFileId().split(",");
for (int i = 0; i < ids.length; i++) {
//获取所有文件
UploadFile uploadFile = bo.getUploadFile(ids[i]);
for (Person person : personList) {
//拼接文件名称
uploadFileNames.add(person.getName()+"-"+person.getAccount()+"-"+uploadFile.getUploadFileName());
}
//获取存储文件名
String storageFileName = uploadFile.getStorageFileName();
filePaths.add(path + File.separator + storageFileName);
}
}
}
File[] files = new File[filePaths.size()];
for (int i = 0; i < filePaths.size(); i++) {
files[i] = new File(filePaths.get(i));// 获取所有需要下载的pdf
}
// 创建临时压缩文件
File file = new File(path + File.separator + "ZIP" + "\\" + "项目申报材料.zip");
try {
//判断文件是否存在
if (!file.exists()) {
//创建父级文件
file.getParentFile().mkdir();
//创建压缩文件
file.createNewFile();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
ZipOutputStream zos = new ZipOutputStream(bos);
ZipEntry ze = null;
for (int i = 0; i < files.length; i++) {// 将所有需要下载的pdf文件都写入临时zip文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(files[i]));
for(int j=0;j<uploadFileNames.size();j++){
String uploadFileName = uploadFileNames.get(i);
ze = new ZipEntry(uploadFileName);
}
zos.putNextEntry(ze);
int s = -1;
while ((s = bis.read()) != -1) {
zos.write(s);
}
bis.close();
}
zos.flush();
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
response.setContentType("application/x-download");// 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
String string = new String("项目申报材料.zip".getBytes("GBK"), "ISO8859_1");
response.setHeader("Content-Disposition", "attachment;filename="+string+"");// 下载文件的名称
response.setCharacterEncoding("UTF-8");
ServletOutputStream servletOutputStream = response.getOutputStream();
DataOutputStream temps = new DataOutputStream(servletOutputStream);
String filePath = file.getPath();
DataInputStream in = new DataInputStream(new FileInputStream(filePath));// 浏览器下载文件的路径
byte[] b = new byte[2048];
File reportZip = new File(filePath);// 之后用来删除临时压缩文件
try {
while ((in.read(b)) != -1) {
temps.write(b);
}
temps.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (temps != null)
temps.close();
if (in != null)
in.close();
if (reportZip != null)
reportZip.delete();// 删除服务器本地产生的临时压缩文件
servletOutputStream.close();
}
return NONE;
}
根据个人需要修改
参考修改