输出的文件层级关系如下:
主要功能代码如下:
@Override
public void getZipData(Map<String, String> map, HttpServletResponse response) {
OutputStream out = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
FileInputStream is = null;
BufferedInputStream bis = null;
try {
String filename = "最终的压缩包名称.zip";
out = new FileOutputStream("c:/temp/" + filename);
bos = new BufferedOutputStream(out);
zos = new ZipOutputStream(bos);
// 解决中文文件名乱码
zos.setEncoding("GBK");
// allList 每次循环是压缩包下的一个文件夹
for (allList) {
// 将每一个报销单中的所有附件放在同一个文件夹下面
// 获取每个文件夹的名字
String dirsName = "每个文件夹的名称";
// 每个循环是一个文件夹中的文件
for (atts) {
String fdFileName = att.getFdFileName();
if(StringUtil.isNull(fdFileName)){
fdFileName = "文件名为空.zip";
}
InputStream inputStream = xxxx;
File file = new File(fdFileName);
inputStream2File(inputStream, file);
is = new FileInputStream(file);
bis = new BufferedInputStream(is);
//会在压缩文件中建立名字为dirsName的文件夹,并在文件夹里创建文件
zos.putNextEntry(new ZipEntry(dirsName + "/" + file.getName()));
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = bis.read(cache)) != -1) {
zos.write(cache, 0, nRead);
}
zos.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(bis);
IOUtils.closeQuietly(is);
try {
if (zos != null) {
zos.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
IOUtils.closeQuietly(zos);
IOUtils.closeQuietly(bos);
IOUtils.closeQuietly(out);
}
}
private static void inputStream2File (InputStream is, File file) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[8192];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} finally {
os.close();
is.close();
}
}
以上代码实现将文件打包下载到指定目录下, 如果需要下载到浏览器再添加如下代码:
通过浏览器下载:
public void downloadLaborReportData(HttpServletResponse response) {
String zipFileName = "附件导出.zip";
String fileUrl = "c:/temp/" + zipFileName;
OutputStream out = null;
FileInputStream fis = null;
try {
out = response.getOutputStream();
File file = new File(fileUrl);
fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
fis.close();
// 设置响应头
response.setContentType("application/zip");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(zipFileName, "UTF-8"));
out.write(buffer);
out.flush();
//删除服务器上的临时文件
File deleteFile = new File(fileUrl);
if (deleteFile.delete()) {
logger.debug("临时文件" + zipFileName + "删除成功");
} else {
logger.debug("临时文件" + zipFileName + "删除失败");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(out);
}
}
以上便是基于java ZipOutputStream 下载多级.zip文件的全部内容了!
补充一下用法:
// 先下载到c:/temp临时位置
this.getZipData(conditionMap, response);
// 再从c:/temp读取下载到浏览器
this.downloadLaborReportData(response);