zip工具类:
/**
* 把文件打成压缩包并输出到客户端浏览器中
*/
public static void downloadZipFiles(HttpServletResponse response, List<String> srcFiles, String zipFileName) {
try {
response.reset(); // 重点突出
response.setCharacterEncoding("UTF-8"); // 重点突出
response.setContentType("application/x-msdownload"); // 不同类型的文件对应不同的MIME类型 // 重点突出
// 对文件名进行编码处理中文问题
zipFileName = new String(zipFileName.getBytes(), StandardCharsets.UTF_8);
// inline在浏览器中直接显示,不提示用户下载
// attachment弹出对话框,提示用户进行下载保存本地
// 默认为inline方式
response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
// --设置成这样可以不用保存在本地,再输出, 通过response流输出,直接输出到客户端浏览器中。
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
zipFile(srcFiles, zos);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 压缩文件
*
* @param filePaths 需要压缩的文件路径集合
* @throws IOException
*/
private static void zipFile(List<String> filePaths, ZipOutputStream zos) {
//设置读取数据缓存大小
byte[] buffer = new byte[4096];
try {
//循环读取文件路径集合,获取每一个文件的路径
for (String filePath : filePaths) {
File inputFile = new File(filePath);
//判断文件是否存在
if (inputFile.exists()) {
//判断是否属于文件,还是文件夹
if (inputFile.isFile()) {
//创建输入流读取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
//将文件写入zip内,即将文件进行打包
zos.putNextEntry(new ZipEntry(inputFile.getName()));
//写入文件的方法,同上
int size = 0;
//设置读取数据缓存大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
//关闭输入输出流
zos.closeEntry();
bis.close();
} else { //如果是文件夹,则使用穷举的方法获取文件,写入zip
File[] files = inputFile.listFiles();
List<String> filePathsTem = new ArrayList<String>();
for (File fileTem : files) {
filePathsTem.add(fileTem.toString());
}
zipFile(filePathsTem, zos);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != zos) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
controller:
/**
* @description: zip
* @return: com.ddkj.common.utils.RetMessage
* @author: Jay
* @date: 2019-12-27 14:15
*/
@RequestMapping("/packageZip")
public RetMessage packageZip(@RequestParam Map<String, Object> params, HttpServletResponse respons){
EntityWrapper<PbFileEntity> wrapper = new EntityWrapper<>();
if(params.get("repairTaskId") != null ){
if(params.get("type") != null){
wrapper.eq("type",params.get("type"));
wrapper.eq("repair_task_id",params.get("repairTaskId"));
List<PbFileEntity> pbFileEntities = pbFileService.selectList(wrapper);
List<String> list = new ArrayList<>();
if (pbFileEntities != null && pbFileEntities.size()>0) {
for (PbFileEntity pbFileEntity : pbFileEntities) {
list.add(pbFileEntity.getUrl());
}
}
if(list != null && list.size()>0){
FileUtils.downloadZipFiles(respons,list,"image.zip");
return null;
}
}
}
return RetMessage.error();
}
该博客详细介绍了如何在SpringBoot应用中利用Java实现多文件的压缩,并通过流的方式提供下载。内容涵盖了一个zip工具类的创建以及在controller中的具体使用方法,旨在帮助开发者理解并实现在Web环境中进行文件压缩与下载的功能。
2132





