前言
使用zip4j下载文件并加密压缩
一、服务器文件批量下载zip加密压缩文件
二、使用步骤
1.引入库
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
2.压缩文件并加密
public class ZipUtils {
public static void createZipFile(String zipPath, String passWd, ArrayList<File> files )
throws ZipException {
ZipFile zipFile = new ZipFile(zipPath);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(passWd);
zipFile.addFiles(files, parameters);
}
}
3.下载压缩文件
@GetMapping("/exportZip")
public void exportZip(HttpServletResponse response,Long[] ids) throws Exception {
Set<String> list = demoService.selectByIds(ids);
if(CollectionUtils.isEmpty(atlasList)){
throw new Exception("无数据");
}
String zipPath = savePath+"/"+System.currentTimeMillis()+".zip";
String mobile = demoService.getMobile(SecurityUtils.getUserId());
String passWd;
if(StringUtils.isBlank(mobile)){
passWd = "123456";
}else {
passWd = mobile.substring(5,11);
}
ArrayList<File> files = new ArrayList<>();
list.stream().forEach(
url-> files.add(new File(savePath+url))
);
ZipUtils.createZipFile(zipPath, passWd,files);
try {
String fileName = URLEncoder.encode(System.currentTimeMillis()+".zip", "UTF-8");
try {
FileInputStream fileInputStream = new FileInputStream(zipPath);
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
response.setContentType("application/zip");
OutputStream outputStream = response.getOutputStream();
IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
FileUtil.del(zipPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}