将文件以压缩包的形式进行下载,压缩包中根据不同类型文件创建不同的文件夹

252 阅读1分钟

1、根据文件路径将不同类型文件写入到zipOutputStream流中

//注意进行文件流写入之前要设置编码格式,否则下载成功在解压时会出现乱码
zipOutputStream.setEncoding("gbk");

//将文件写入到zipOutputStream流
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;filename="+ new String(fileName.getBytes("GB2312"),"iso8859-1"));
 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);
 }
}