层级目录
市北区
–张三
----社保材料
----医保材料
------文件.jpg
------文件2.jpg
public static void main(String[] args) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//压缩输出流
ZipOutputStream zip = new ZipOutputStream(outputStream);
OSS aliOSS = OssConfig.getAliOSS();
//获取有文件id的个人信息
List<SoldierInfo> soldierInfoList = new LinkedList();
for (SoldierInfo soldierInfo : soldierInfoList) {
//获取文件的id 集合 我的文件存储是 1,2,3 这样的存储的文件id
String medicalInsuranceFile = soldierInfo.getMedicalInsuranceFile();
if (StringUtils.isNotEmpty(medicalInsuranceFile)) {
String[] ids = medicalInsuranceFile.split(",");
//通过id 获取到文件在oss 的地址标识
LinkedList<String> processFileIds = new LinkedList<String>(Arrays.asList(ids));
//获取文件列表
List<ProcessFile> fileList = new ArrayList<>();
for (ProcessFile processFile : fileList) {
//创建虚拟路径 也就是压缩包里面的地址
String fileName = soldierInfo.getSettingPlace() + File.separator + soldierInfo.getName() + File.separator + "医保" + File.separator + processFile.getName();
//这一行的意思 理解为占位 确保压缩文件里有这样的一个文件存在了
zip.putNextEntry(new ZipEntry(fileName));
//获取oss 上的文件的输入流
OSSObject object = aliOSS.getObject(OssConfig.getBucketName(), processFile.getPath());
InputStream inputStream = object.getObjectContent();
//转为字节流 写入到 压缩输出流中
byte[] bytes = IoUtil.readBytes(inputStream);
IOUtils.write(bytes, zip);
//刷新关闭
zip.flush();
zip.closeEntry();
}
//如果有多种文件可以再写一个for
}
}
//关闭
IOUtils.closeQuietly(zip);
String zipName = "文件材料.zip" + IdUtils.fastSimpleUUID();
byte[] bytes = outputStream.toByteArray();
//前端下载 response 是HttpServletResponse
//这行代码一般写在controller 层里面
genCode(response, bytes, zipName);
}
genCode()
/**
* 生成zip文件
*/
private static void genCode(HttpServletResponse response, byte[] data, String zipName) throws IOException {
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}