1、根据文件路径将不同类型文件写入到zipOutputStream流中
zipOutputStream.setEncoding("gbk");
int leng = nameList.size();
for (int i = 0; i < leng; i++) {
String rootFilePath = realFilePathList.get(i);
String imageName = nameList.get(i);
String downloadFileName = rootFilePath + imageName.substring(1, imageName.length() - 1);
File file = new File(downloadFileName);
if (!file.exists()) {
logger.info("================"+downloadFileName + "文件不存在======================");
continue;
}
downloadFileName = newRealFileNameList.get(i);
if (!"全部".equals(fileVersion)) {
zipOutputStream.putNextEntry(new ZipEntry(new String(downloadFileName.getBytes("GB2312"), "gbk")));
} else {
String version = "1".equals(selOldOrNewVersion) ? "最新版本" : "历次版本";
zipOutputStream.putNextEntry(new ZipEntry(version + File.separator + downloadFileName));
}
int len;
byte[] b = new byte[1024];
InputStream inputStream = new FileInputStream(file);
try{
while ((len = inputStream.read(b)) != -1) {
zipOutputStream.write(b, 0, len);
}
}catch (Exception e){
logger.error("写入zipOutputStream流时发生异常",e);
}finally {
if(inputStream != null){
inputStream.close();
}
}
}
2、将流响应给浏览器进行下载
//压缩包名字
String fileName =billType+"-"+code+fileVersion+"附件信息"+".zip"
response.setContentType("application/x-msdownload")
response.setHeader( "Content-Disposition","attachment
zipOutputStream.flush()
zipOutputStream.closeEntry()
zipOutputStream.setEncoding("gbk")
zipOutputStream.finish()
byte[] ba = byteArrayOutputStream.toByteArray()
if (ba != null) {
servletOutputStream.write(ba)
}
servletOutputStream.flush()
} catch (AccessoriesConfigException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
} finally {
try{
servletOutputStream.close()
byteArrayOutputStream.close()
zipOutputStream.close()
}catch (Exception e){
logger.error("关闭流异常",e)
}
}